文章目录
1.介绍
1.1 主要功能
1.实现了所有HTTP的方法(get、post、put、head等)
2.支持自动转向
3.支持代理服务器
4.自动处理set-cookie中的cookie
5.直接获取服务器发送的response code和headers
6.设置连接超时的能力
需要注意的是,httpclient版本的不同,功能实现的代码也就不同,需要谨慎。
1.2 步骤
-
创建HttpClient对象。
-
创建请求方法的实例,并指定请求URL。如果需要发送GET请求, 创建HttpGet对象; 如果需要发送POST请求,创建HttpPost对象。
-
如果需要发送请求参数, 可调用HttpGet、 HttpPost共同的setParams(HetpParams params)方法来添加请求参数; 对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
-
调用HttpClient对象的execute(HttpUriRequest request)发送请求该方法返回一个HttpResponse。
-
调用HttpResponse的getAllHeaders()、 getHeaders(String name)等方法可获取服务器的响应头; 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。 程序可通过该对象获取服务器的响应内容。
-
释放连接。 无论执行方法是否成功, 都必须释放连接。
2.使用
2.1 get访问(不带参数)
@Test
public void get() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8080/ssm_crud/depts");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("content = " + content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();//关闭连接
httpClient.close();//关闭浏览器
}
}
日志参考:slf4j以及实现类
2.2 get访问(带参数)
@RequestMapping("/depts")
@ResponseBody
public Msg getDepts(@RequestParam("deptName")String deptName){
//查出的所有部门信息
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts", list).add("deptName",deptName);
}
@Test
public void getWithParam() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/ssm_crud/depts");
uriBuilder.setParameter("deptName","NewDeptAAAAA");//中文的话,会乱码,要么设置tomcat,要么两次转码
HttpGet httpGet = new HttpGet(uriBuilder.build());
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("content = " + content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();//关闭连接
httpClient.close();//关闭浏览器
}
}
2.3 post访问(不带参数)
@RequestMapping("/depts")
@ResponseBody
public Msg getDepts(){
//查出的所有部门信息
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts", list);
}
@Test
public void post() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/ssm_crud/depts");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("content2 = " + content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();//关闭连接
httpClient.close();//关闭浏览器
}
}
2.4 post访问(带参数)
@RequestMapping("/depts2")
@ResponseBody
public Msg getDepts2(@RequestParam("deptName")String deptName){
//查出的所有部门信息
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts", list).add("deptName",deptName);
}
@Test
public void postWithParam() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/ssm_crud/depts2");
List<NameValuePair> param = new ArrayList<>();
param.add(new BasicNameValuePair("deptName","新部门"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(param, "utf-8");
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("content2 = " + content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();//关闭连接
httpClient.close();//关闭浏览器
}
}
2.5 连接池
@RequestMapping("/depts")
@ResponseBody
public Msg getDepts(){
//查出的所有部门信息
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts", list);
}
@Test
public void conPool() throws Exception {
PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
//设置最大连接数
pool.setMaxTotal(100);
//设置每个主机的最大连接数
pool.setDefaultMaxPerRoute(10);
doGet(pool);
doGet(pool);
}
private void doGet(PoolingHttpClientConnectionManager pool) throws Exception {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pool).build();
HttpGet httpGet = new HttpGet("http://localhost:8080/ssm_crud/depts");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("content2 = " + content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();//关闭连接
// httpClient.close();//不能关闭
}
}
2.6 请求参数配置
@Test
public void get() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8080/ssm_crud/depts");
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)//创建连接最长时间
.setConnectionRequestTimeout(500)//获取连接最长时间
.setSocketTimeout(10 * 1000)//数据传输最长时间
.build();
httpGet.setConfig(config);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("content2 = " + content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();//关闭连接
httpClient.close();//关闭浏览器
}
}
参考
httpClient 官网
HttpClient详细使用示例
HttpClient 详细介绍
dvd