1.Apache HttpClien总结
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/32bbadf7c8732b51b827dad2fa559b61.png)
2.Apache HttpClien 测试
public static void testHttpClientGet(){
CloseableHttpClient httpClient =null;
CloseableHttpResponse response =null;
HttpEntity entity = null;
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://127.0.0.1:9005/user_all?id=2");
httpGet.setHeader("Connection","keep-alive");
response = httpClient.execute(httpGet);
System.out.println("response = " + response.getStatusLine());
entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println("result = " + result);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
if (httpClient!=null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response!=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static final int CONNECT_TIMEOUT = 5000;
private static final int SOCKET_TIMEOUT = 5000;
public static void testHttpClientPost() throws UnsupportedEncodingException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://127.0.0.1:9005/user_form");
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
post.setConfig(requestConfig);
List<BasicNameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("start","1"));
params.add(new BasicNameValuePair("end","3"));
post.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println("string = " + string);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpClient!=null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response!=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}