HTTP Body

2019-07-15  本文已影响0人  DataSource
 public static void main(String[] args) {
        JSONObject jsobj1 = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsobj1.put("pcscode",jsonArray);
        JSONObject data = JSON.parseObject( post(jsobj1,"url"));
        System.out.println(data);
    }
    
    public static String post(JSONObject json,String URL) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        AtomicReference<String> result = new AtomicReference<>("");
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = "";
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result.set(strber.toString());
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功,做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        return result.get();
    }
上一篇下一篇

猜你喜欢

热点阅读