基于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 "";
}
}