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;
}
}
httpclient4.5调用接口
最新推荐文章于 2021-07-14 13:59:05 发布