HTTP Body

作者: DataSource | 来源:发表于2019-07-15 17:00 被阅读0次
 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();
    }

相关文章

网友评论

      本文标题:HTTP Body

      本文链接:https://www.haomeiwen.com/subject/evxokctx.html