Java中发送Http请求之httpClient
HTTP 协议是 Internet 上使用得最多、最重要的协议之一,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源, JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活.
1 httpClient的简介
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient.
其主要特性:
- 实现了所有 HTTP 的方法(GET,POST,PUT,DELETE,HEAD 等)
- 支持自动转向
- 支持 HTTPS 协议
- 支持代理服务器(Nginx等)
使用步骤:
1 创建HttpClient对象
2 创建请求方法对象, 如发送GET请求, 则创建HttpGet对象; 如发送POST请求,则创建HttpPost对象
3 添加请求参数,可通过setParams方法添加普通请求参数, 对于POST请求,请求体参数,采用setEntity方法添加请求体参数
4 使用HttpClient对象的execute方法发送请求,返回HttpResponse响应对象
5 响应对象HttpResponse的方法, 可以获取服务器的响应头,响应体等信息
2 httpClient的案列
@Slf4j
public class HttpClientDemo {
// 使用HttpClients工具类生成
// HttpClient httpClient = HttpClients.createDefault();
/**
* 无参GET请求
*/
public static String doGetTestByNotParam() {
String url = "http://localhost:8889/consumer/get";
// 1 获取httpClient客户端
HttpClient httpClient = HttpClients.createDefault();
HttpClient httpClient = HttpClientBuilder.create().build();
// 2 创建请求
HttpGet httpGet = new HttpGet(url);
// 3 发送请求
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
// 4 响应状态码 响应信息
int statusCode = httpResponse.getStatusLine().getStatusCode();
log.info("响应状态码为: {} ", statusCode);
// 响应信息
HttpEntity httpEntity = httpResponse.getEntity();
log.info("响应内容为: {} ", EntityUtils.toString(httpEntity));
//释放资源
EntityUtils.consume(httpEntity);
return EntityUtils.toString(httpEntity);
} catch (IOException e) {
log.info("请求异常, 错误信息为: {} ", e.getMessage());
return null;
}
}
/**
* 有参GET请求 添加请求配置
*/
public static String doGetTestByParam() {
String url = "http://localhost:8889/consumer/get";
String param = "key=1234545&id=123123123";
// 获取httpClient客户端
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建GET请求
HttpGet httpGet = new HttpGet(url + "?" + param);
// 配置请求信息
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 连接超时时间
.setConnectionRequestTimeout(5000) //请求超时时间
.setSocketTimeout(5000) // 读写超时时间
.setRedirectsEnabled(true) // 是否重定向 默认true开启
.build();
httpGet.setConfig(requestConfig);
// 发送请求
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
// 4 响应状态码 响应信息
int statusCode = httpResponse.getStatusLine().getStatusCode();
log.info("响应状态码为: {} ", statusCode);
// 响应信息
HttpEntity httpEntity = httpResponse.getEntity();
log.info("响应内容为: {} ", EntityUtils.toString(httpEntity));
//释放资源
EntityUtils.consume(httpEntity);
return EntityUtils.toString(httpEntity);
} catch (IOException e) {
log.info("请求异常, 错误信息为: {} ", e.getMessage());
return null;
}
}
/**
* 有参GET请求 添加请求配置
*/
public static String doGetTestByURI() {
String url = "http://localhost:8889/consumer/get";
String param = "key=1234545&id=123123123";
// 获取httpClient客户端
HttpClient httpClient = HttpClientBuilder.create().build();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("key", "123456"));
params.add(new BasicNameValuePair("id", "123123"));
// 发送请求
HttpResponse httpResponse = null;
URI uri = null;
try {
uri = new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(8898)
.setPath("/test")
.setParameters(params)
.build();
// 创建GET请求
HttpGet httpGet = new HttpGet(uri);
httpResponse = httpClient.execute(httpGet);
// 配置请求信息
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 连接超时时间
.setConnectionRequestTimeout(5000) //请求超时时间
.setSocketTimeout(5000) // 读写超时时间
.setRedirectsEnabled(true) // 是否重定向 默认true开启
.build();
httpGet.setConfig(requestConfig);
// 4 响应状态码 响应信息
int statusCode = httpResponse.getStatusLine().getStatusCode();
log.info("响应状态码为: {} ", statusCode);
// 响应信息
HttpEntity httpEntity = httpResponse.getEntity();
log.info("响应内容为: {} ", EntityUtils.toString(httpEntity));
//释放资源
EntityUtils.consume(httpEntity);
return EntityUtils.toString(httpEntity);
} catch (Exception e) {
log.info("请求异常, 错误信息为: {} ", e.getMessage());
return null;
}
}
/**
* 无参POST请求
*/
public static String doPostTestByNotParam() {
// 请求地址
String url = "http://localhost:8889/consumer/post";
// 获取httpClient客户端
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建请求
HttpPost httpPost = new HttpPost(url);
// 发送请求
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
// 响应状态码 响应信息
int statusCode = httpResponse.getStatusLine().getStatusCode();
log.info("响应状态码为: {} ", statusCode);
// 响应信息
HttpEntity httpEntity = httpResponse.getEntity();
log.info("响应内容为: {} ", EntityUtils.toString(httpEntity));
//释放资源
EntityUtils.consume(httpEntity);
return EntityUtils.toString(httpEntity);
} catch (IOException e) {
log.info("请求异常, 错误信息为: {} ", e.getMessage());
return null;
}
}
/**
* 有参POST请求
*/
public static String doPostTestByParam() {
// 请求地址
String url = "http://localhost:8889/consumer/post";
// post请求
HttpClient httpClient = null;
HttpPost postMethod = null;
HttpResponse response = null;
String responseContent = null;
try {
// 获取http客户端
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);
// 自定义对象
User user = new User();
// 设置请求头
postMethod.addHeader("Content-Type", "application/json;charset=utf8");
// 封装请求体
postMethod
.setEntity(new StringEntity(JSON.toJSONString(user), Charset.forName("UTF-8")));
// 发送请求
response = httpClient.execute(postMethod);
// 获取响应结果
int statusCode = response.getStatusLine().getStatusCode();
// 响应对象
HttpEntity httpEntity = response.getEntity();
// 响应的字符串
responseContent = EntityUtils.toString(httpEntity, "UTF-8");
//释放资源
EntityUtils.consume(httpEntity);
return responseContent;
} catch (IOException e) {
log.info("请求异常, 错误信息为: {} ", e.getMessage());
return null;
}
}
}
HttpClients对象
HttpClients的createDefault()方法,也是调用了HttpClientBuilder.create().build();构造器模式创建了一个CloseableHttpClient对象.
public class HttpClients {
private HttpClients() {
}
public static HttpClientBuilder custom() {
return HttpClientBuilder.create();
}
public static CloseableHttpClient createDefault() {
return HttpClientBuilder.create().build();
}
public static CloseableHttpClient createSystem() {
return HttpClientBuilder.create().useSystemProperties().build();
}
public static CloseableHttpClient createMinimal() {
return new MinimalHttpClient(new PoolingHttpClientConnectionManager());
}
public static CloseableHttpClient createMinimal(HttpClientConnectionManager connManager) {
return new MinimalHttpClient(connManager);
}
}
CloseableHttpClient对象
它是HttpClient接口的唯一抽象类.发送请求时,调用execute方法,
public abstract class CloseableHttpClient implements HttpClient, Closeable {
private final Log log = LogFactory.getLog(this.getClass());
public CloseableHttpClient() {
}
public CloseableHttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException {
return this.execute(request, (HttpContext)null);
}
public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
Args.notNull(request, "HTTP request");
return this.doExecute(determineTarget(request), request, context);
}
protected abstract CloseableHttpResponse doExecute(HttpHost var1, HttpRequest var2, HttpContext var3) throws IOException, ClientProtocolException;
}
HttpGet对象
继承自HttpRequestBase对象,HttpGet请求对象,用来发送GET请求. 查阅代码,发现其构造方法有如下三种.
public class HttpGet extends HttpRequestBase {
public static final String METHOD_NAME = "GET";
public HttpGet() {
}
public HttpGet(URI uri) {
this.setURI(uri);
}
public HttpGet(String uri) {
this.setURI(URI.create(uri));
}
public String getMethod() {
return "GET";
}
}
HttpPost对象
继承自HttpEntityEnclosingRequestBase对象,HttpPost请求对象,用来发送POST请求. 查阅代码,发现其构造方法有如下三种.
public class HttpPost extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "POST";
public HttpPost() {
}
public HttpPost(URI uri) {
this.setURI(uri);
}
public HttpPost(String uri) {
this.setURI(URI.create(uri));
}
public String getMethod() {
return "POST";
}
}
HttpResponse对象
请求响应对象, 主要使用的是其实现类BasicHttpResponse.
public interface HttpResponse extends HttpMessage {
StatusLine getStatusLine();
void setStatusLine(StatusLine var1);
void setStatusLine(ProtocolVersion var1, int var2);
void setStatusLine(ProtocolVersion var1, int var2, String var3);
void setStatusCode(int var1) throws IllegalStateException;
void setReasonPhrase(String var1) throws IllegalStateException;
HttpEntity getEntity();
void setEntity(HttpEntity var1);
Locale getLocale();
void setLocale(Locale var1);
}
BasicHttpResponse对象
其中常用的属性有StatusLine响应状态码,HttpEntity响应信息对象等.
public class BasicHttpResponse extends AbstractHttpMessage implements HttpResponse {
// 状态码
private StatusLine statusline;
private ProtocolVersion ver;
private int code;
private String reasonPhrase;
// 响应信息对象
private HttpEntity entity;
private final ReasonPhraseCatalog reasonCatalog;
private Locale locale;
// ...
}