简单的使用httpclient调接口发送和接收JSon
2017-09-08 17:36
295 查看
由于项目需要,需要用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 工具类调取。这里就不列出了
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 工具类调取。这里就不列出了
相关文章推荐
- RabbitMQ C++客户端 RabbitMQ Client for Windows/Linux 超简单接收发送接口-最近更新2018-02-28
- 使用firefox插件httperrequest,模拟发送及接收Json请求 【转】
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- 使用HTTPClient发送简单request请求
- httpClient使用,1 发送post请求 2 发送get请求取得接口中的数据
- 使用setsockopt()接口,设置TCP的接收与发送超时,Invalid argument错误问题
- 使用afnetworking和网络服务接口及soap发送并接收http/https请求:
- 简单文本消息交互接口之使用json
- 使用HttpClient发送请求、接收响应
- 爬虫中使用HttpClient发送ajax请求,并处理返回的JSON字符串
- 使用HttpRequester发送json请求测试接口
- howto使用http接收和发送简单的xml请求
- httpClient 使用post方法提交json数据,接收返回数据实例
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- 使用firefox插件httperrequest,模拟发送及接收Json请求
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- php接口接收发送数据(json)
- 用eclipse建立简单WebService客户端,使用WSDL,用于短信接口发送
- 使用httperrequest,模拟发送及接收Json请求
- 使用setsockopt()接口,设置TCP的接收与发送超时,Invalid argument错误问题