由于项目需要,需要用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 工具类调取。这里就不列出了
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/17483.html