您的位置:首页 > 理论基础 > 计算机网络

HttpClient发送后台请求

2015-10-28 10:09 381 查看
由于API的不断更新,所以创建HttpClient对象和设置超时代理方式也会有细微区别

// 3.X版本
HttpClient httpClient=new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接超时时间,毫秒

//4.3版本
CloseableHttpClient httpClient = HttpClients.createDefault();

//或者使用HttpClientBuilder对象
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

//请求地址
HttpPost post = new HttpPost(url);
//设置代理和超时
RequestConfig config=RequestConfig.custom().setConnectionRequestTimeout(30000).setProxy(httpProxyHost).build();
post.setConfig(config);


详细变更请参考API文档,这里直接将实例

/**
* web 请求/响应 API类
*/
public class WebUtil {

/**
* post 请求
*
* @param url
*            请求路径
* @param params
*            请求参数
* @return 请求返回
*/
public String post(String url, List<BasicNameValuePair> params) {
PayLog.addLog(ELogAction.Post, EPayLogType.PostRequest, new Object[] { url, params });

if (CheckValue.valideteNullOrEmpty(url) || params == null || params.isEmpty()) {
return "";
}

String result = "";
ProxyUtil proxyUtil=HttpRequestHelper.getProxyUtil();

// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
//请求地址
HttpPost post = new HttpPost(url);
RequestConfig config=null;
//如果需要设置代理
if (proxyUtil.getIsEnable()) {
HttpHost httpProxyHost=new HttpHost(proxyUtil.getHost(),proxyUtil.getPort(),"http");
config=RequestConfig.custom().setConnectionRequestTimeout(30000)
.setProxy(httpProxyHost).build();
}
else
{
//超时时间设置为30s
config=RequestConfig.custom().setConnectionRequestTimeout(30000).build();
}
//设置请求超时时间和有可能设置代理
post.setConfig(config);
try {
post.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
CloseableHttpResponse response = closeableHttpClient.execute(post);

result = parseResponse(response.getEntity().getContent());
PayLog.addLog(ELogAction.Post, EPayLogType.PostResponse, result);

// 释放资源
closeableHttpClient.close();
} catch (Exception ex) {

PayLog.addErrorLog(ELogAction.Post, EPayLogType.PostResponse, ex.getMessage());
result = "未知错误,请联系客服!";
}
return result;
}

/**
* 解析Response信息
*
* @param respStream
*            response stream
* @return
*/
protected String parseResponse(InputStream respStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(respStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
respStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

/**
* 将Response信息转为Json格式
*
* @param response
*            eg:param1=v1¶m2=v2¶m3=v3 ...
* @return
*/
public String responseToJson(String response) {
if (CheckValue.valideteNullOrEmpty(response)) {
return "";
}

Map<String, String> map = new HashMap<String, String>();

String[] responseParams = response.split("&");
String key = "";
String value = "";
for (String string : responseParams) {
String[] keyValues = string.split("=");
if (keyValues != null && keyValues.length > 0) {
key = keyValues[0];
}

if (keyValues != null && keyValues.length > 1) {
value = keyValues[1];
} else {
value = "";
}
map.put(key, value);
}
Gson gson = new Gson();
return gson.toJson(map);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: