简单的使用httpclient调接口发送和接收JSon

  • Post author:
  • Post category:其他




由于项目需要,需要用httpclient调其他部门的接口获取信息,学习了httpclient的使用方法,demo大概代码如下:


 public static List<Object> doPost(String url, JSONObject json, String infoname, Class cl){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        List<Object> list=new ArrayList();
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                System.out.println(result);
                response = JSONObject.parseObject(result);
                List<JSONObject> info = (List) response.get(infoname);

                for (JSONObject s1 : info) {
                    Object netDownData = (Object) JSONObject.toJavaObject(s1, cl);
                    list.add(netDownData);

                }

            }else{
                    logger.error("拉取失败,错误编码为:"+res.getStatusLine().getStatusCode());
                }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;
    }



写完后,发现可以使用HttpUtil 工具类调取。这里就不列出了



版权声明:本文为qq_36752632原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。