httpclient4.5调用接口
发布日期:2022-02-09 20:39:06 浏览次数:12 分类:技术文章

本文共 3243 字,大约阅读时间需要 10 分钟。

import net.sf.json.JSONObject; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpUtil {
/** * 获取接口返回值 * @param url * @return * @see [类、类#方法、类#成员] */ public static JSONObject getApiData(String url, List
paramList) {
//这里开始用于httpclient3.1升级到4.5修改,如果有问题 将下面原来的实现方式还原 JSONObject result = new JSONObject(); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; int code = -1; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build(); //创建请求 HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//设置请求头 try {
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));//设置请求参数 httpPost.setConfig(requestConfig);//设置超时时间 httpPost.releaseConnection();//这里应该是让连接可以重用 // 创建默认的httpClient实例. httpClient = HttpClients.createDefault(); // 发送请求开始时间 long starttime = System.currentTimeMillis(); // 执行请求 response = httpClient.execute(httpPost); // 发送请求结束时间 long endtime = System.currentTimeMillis(); entity = response.getEntity(); // 获取请求返回的状态码 code = response.getStatusLine().getStatusCode(); responseContent = EntityUtils.toString(entity, "UTF-8"); result = JSONObject.fromObject(responseContent); } catch (UnsupportedEncodingException e) {
LOG.error("Order find UnsupportedEncodingException error..."); } catch (ClientProtocolException e) {
LOG.error("Order find ClientProtocolException error..."); } catch (IOException e) {
LOG.error("Order find IOException error..."); } finally {
try {
if (response != null) {
response.close(); } } catch (IOException e) {
LOG.error("response close error " + e.getMessage()); } try {
if (null != httpClient) {
httpClient.close(); } } catch (IOException e) {
LOG.error("httpClient close error " + e.getMessage()); } } return result; } }

转载地址:https://blog.csdn.net/iteye_12884/article/details/82673583 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:使用spring加载properties文件
下一篇:DB Connection

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月02日 16时05分59秒