java中使用HttpClient调用接口
欢迎关注蚕豆公众号,不定时分享技术。同时欢迎加入蚕豆技术群哦,扫描公众号点击关于作者加群~~~~
1.HttpClient 提供的主要的功能
(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
直接言归正传了!!!!上代码
public static String sendPutForm(String url, Map<String,String> map, String encoding) throws ParseException, IOException {
String body = "";
// 打印了一下我推送的json数据
log.info("我推送的json数据:" + map);
log.info("我推送的url:" + url);
CloseableHttpResponse response = null;
///获得Http客户端
CloseableHttpClient client = HttpClients.createDefault();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 配置信息
// 设置连接超时时间(单位毫秒)
// 设置请求超时时间(单位毫秒)
// socket读写超时时间(单位毫秒)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000).setConnectionRequestTimeout(50000)
.setSocketTimeout(50000).build();
// 向指定资源位置上传内容// 创建Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setEntity(formEntity);
try {
response = client.execute(httpPost);
// 通过response中的getEntity()方法获取返回值
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
httpPost.abort();
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
log.info("body:" + body);
return body;
}