HttpClient 的用模拟http请求的工具,一般用在测试Http的请求,下面是一个简单的例子:
public void testHttpClient() throws Exception {
String localUrl = "http://127.0.0.1/XXX.html";
//创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(localUrl);
List<NameValuePair> vals = new ArrayList<NameValuePair>();
// 添加参数
vals.add(new BasicNameValuePair("Name","bobobo"));
httpPost.setEntity(new UrlEncodedFormEntity(vals,HTTP.UTF_8));
HttpResponse response = closeableHttpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
System.out.println("status:" + response.getStatusLine());
System.out.println("contentEncoding:" + entity.getContentEncoding());
System.out.println("response content:" + EntityUtils.toString(entity));
}
}
补充一个更详细实例:
protected String httpPostWithJSON(String url, String json) {
String body = StringUtils.EMPTY;
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
int timeout = 15 * 1000;
RequestConfig.Builder requestBuilder = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout);
httpClientBuilder.setDefaultRequestConfig(requestBuilder.build());
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
try {
StringEntity se = new StringEntity(json,Consts.UTF_8);
httpPost.setEntity(se);
HttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
body = EntityUtils.toString(entity,Consts.UTF_8);
}
} catch (UnsupportedEncodingException e) {
logger.error("httpPostWithJSON UnsupportedEncodingException error : ", e);
} catch (ClientProtocolException e) {
logger.error("httpPostWithJSON ClientProtocolException error : ", e);
} catch (IOException e) {
logger.error("httpPostWithJSON IOException error : ", e);
}
return body;
}