HttpClient是Apache HttpComponents项目中的HttpClient模块。
CloseableHttpClient实现了HttpClient和Closeable接口,其中实现Closeable接口后通过调用close()方法以达到关闭流并释放与流相关的所有资源。
2.HttpClient发送请求、接收响应的使用流程
使用Apache HttpClient发送GET和POST请求的步骤(官网说明)。
官网:
Apache HttpClient Example - CloseableHttpClient - JournalDev
1、Create instance of CloseableHttpClient using helper class HttpClients.
使用帮助程序类HttpClients创建CloseableHttpClient实例。
2、Create HttpGet or HttpPost instance based on the HTTP request type.
根据HTTP请求类型创建HttpGet或HttpPost实例。
3、Use addHeader method to add required headers such as User-Agent, Accept-Encoding etc.
使用addHeader方法添加所需的标头,例如User-Agent,Accept-Encoding等。
4、For POST, create list of NameValuePair and add all the form parameters. Then set it to the HttpPost entity.
对于POST,创建NameValuePair列表并添加所有表单参数。 然后将其设置为HttpPost实体。
5、Get CloseableHttpResponse by executing the HttpGet or HttpPost request.
通过执行HttpGet或HttpPost请求来获取CloseableHttpResponse 。
6、Get required details such as status code, error information, response html etc from the response.
从响应中获取所需的详细信息,例如状态代码,错误信息,响应html等。
7、Finally close the apache HttpClient resource.
最后关闭apache HttpClient资源。
详细说明:
(1)使用帮助类HttpClients创建CloseableHttpClient对象.
(2)基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3)使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
(4) 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
(4)调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5)调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
(6)释放连接。无论执行方法是否成功,都必须释放连接。
使用的是Maven,则可以添加以下依赖项,它将包括使用Apache HttpClient所需的所有其他依赖项。
|
HttpClient4.3以上示例 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://www.csdn.net/"); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build(); httpGet.setConfig(requestConfig); httpClient.execute(httpGet); |
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
//请求超时时间,这个时间定义了socket读数据的超时时间,也就是连接到服务器之后到从服务器获取响应数据需要等待的时间,发生超时,会抛出SocketTimeoutException异常。
private static final int SOCKET_TIME_OUT = 60000;
//连接超时时间,这个时间定义了通过网络与服务器建立连接的超时时间,也就是取得了连接池中的某个连接之后到接通目标url的连接等待时间。发生超时,会抛出ConnectionTimeoutException异常
private static final int CONNECT_TIME_OUT = 60000;
/**
* 发送HttpGet请求,不带请求头和请求参数
* @param url
* @return
*/
public static String doGet(String url) throws Exception {
return doGet(url,null);
}
/**
* 发送HttpGet请求,带请求头和请求参数
* @param url
* @param token
* @return
*/
public static String doGet(String url,String token) throws Exception{
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
String result = null;
try {
//1.创建httpClient对象
httpClient = HttpClients.createDefault();
//2.创建httpGet对象
HttpGet httpget = new HttpGet(url);
//2.1设置请求头
httpget.setHeader("Authorization",token);
//2.2对象设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
httpget.setConfig(requestConfig);
//3.使用httpClient发起请求并响应获取repsonse
httpResponse = httpClient.execute(httpget);
// 打印响应状态
System.out.println(httpResponse.getStatusLine());
//4.解析响应,获取数据
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + result);
}
} catch (ParseException | IOException e) {
e.printStackTrace();
}
finally {
//5.释放资源
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
//log.error(e.getMessage(), e);
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
//log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 以post方式调用第三方接口
* @param url
* @param jsonstr
* @return
*/
//public static String doPost(String url, JSONObject json) {
public static String doPost(String url, String jsonstr) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse=null;
String result="";
try {
//1.创建httpClient对象
httpClient = HttpClients.createDefault();
//2.创建httpPost对象
HttpPost httpPost = new HttpPost(url);
//2.1对象设置请求头
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//2.2对象设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
httpPost.setConfig(requestConfig);
//2.3对象设置请求参数
//httpPost.setEntity(new StringEntity(json.toString()));
httpPost.setEntity(new StringEntity(jsonstr));
//3.使用httpClient发起请求并响应获取repsonse
httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
//4.解析响应,获取数据
//判断状态码是否是200
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(entity,ENCODING);
System.out.println(result);
}
System.out.println(httpResponse.getStatusLine());
System.out.println(httpResponse.getStatusLine().getStatusCode());
System.out.println(httpResponse.getProtocolVersion());
System.out.println(HttpStatus.SC_OK);
}
catch (IOException e){
e.printStackTrace();
}
finally {
//5.释放资源
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
//log.error(e.getMessage(), e);
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
//log.error(e.getMessage(), e);
}
}
}
return result;
}
public static void main(String arg[]) throws Exception {
//测试HTTP
//doGet请求
//url 请求地址,如 http://www.baidu.com http://10.1.1.182:8081
HttpClientUtils httputils=new HttpClientUtils();
httputils.doGet("http://10.1.1.182:8081");
//doPost请求
String loginurl="http://10.1.1.182:8081/scheduler/login";
String jsonStr="{\"userName\":\"admin\",\"password\":\"lianShi2020\"}";
//JSONObject json_data = new JSONObject(jsonStr);
String result=httputils.doPost(loginurl, jsonStr);
System.out.println(result);
}
GET执行结果
POST执行结果:
官网例子:
package com.journaldev.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class ApacheHttpClientExample {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://localhost:9090/SpringMVCExample";
private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";
public static void main(String[] args) throws IOException {
sendGET();
System.out.println("GET DONE");
sendPOST();
System.out.println("POST DONE");
}
private static void sendGET() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(GET_URL);
httpGet.addHeader("User-Agent", USER_AGENT);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("GET Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// print result
System.out.println(response.toString());
httpClient.close();
}
private static void sendPOST() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(POST_URL);
httpPost.addHeader("User-Agent", USER_AGENT);
List urlParameters = new ArrayList();
urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));
HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
httpPost.setEntity(postParams);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("POST Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// print result
System.out.println(response.toString());
httpClient.close();
}
}
参考:
httpclient的几个重要的参数 - 简书
HttpClient之请求参数 - IT特工 - 博客园
参考官网翻译:Apache HttpClient示例– CloseableHttpClient_从零开始的教程世界-CSDN博客
https://www.cnblogs.com/zouhong/p/12066741.html
https://zhuanlan.zhihu.com/p/104926682
Java发送http请求方法之CloseableHttpClient
Java发送http请求方法之CloseableHttpClient - wbinbin - 博客园
HttpClient完整使用示例_Java大数据联盟-CSDN博客_httpclient 调用示例
https://blog.csdn.net/qq_41270550/article/details/113698749
接口自动化参考:接口自动化测试 - 随笔分类 - 万春流 - 博客园