当前位置: 代码迷 >> 综合 >> 简单的使用httpclient调接口发送和接收JSon
  详细解决方案

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

热度:88   发布时间:2023-10-28 01:02:59.0

由于项目需要,需要用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数据需要设置contentTypepost.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 工具类调取。这里就不列出了