httpclient4.5调用接口


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<BasicNameValuePair> 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;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值