httpClient实例

基于httpclient4.3.6写的测试客户端,使用PoolingHttpClientConnectionManager 保证线程安全


public class TestHttpClient {

/**
*
*/
@Test
public void testGet() throws IOException {

System.out.println("开始测试");
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();

try {
HttpGet httpget = new HttpGet("http://localhost:8089/httpservice/httpService/testGet");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
InputStream is = response.getEntity().getContent();
String result = getStreamAsString(is, "UTF-8");
System.out.println(result);
} finally {
response.close();
httpget.releaseConnection();
}


HttpPost httpPost = new HttpPost("http://localhost:8089/httpservice/httpService/testPost");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
httpPost.releaseConnection();
}


} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.close();
};


}

private String getStreamAsString(InputStream is, String s) throws IOException {

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(is, s), 8192);

StringWriter writer = new StringWriter();


char[] chars = new char[8192];

int count = 0;

while ((count = reader.read(chars)) > 0) {

writer.write(chars, 0, count);

}


return writer.toString();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {

if (is != null) is.close();

}
return "";
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值