HttpClient 入门教程学习

时间:2021-10-19 16:08:29

HttpClient简介

HttpClient是基于HttpCore的HTTP/1.1兼容的HTTP代理实现。 它还为客户端认证,HTTP状态管理和HTTP连接管理提供可重用组件。 HttpComponents Client是Commons HttpClient 3.x的继任者和替代者。 强烈建议Commons HttpClient的用户进行升级。

HttpClient HTTP Get请求

/**
* httpClient Get请求
*/
public static void main(String[] args) throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Get 请求 Url
HttpGet httpget = new HttpGet("http://httpbin.org/get"); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; //第三步 执行请求
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}

HttpClient HTTP Post请求

/**
* httpClient Post请求
*/
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Post 请求 Url
HttpPost httpPost = new HttpPost("http://httpbin.org/post"); // 装配post请求参数
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("age", "20")); //请求参数
list.add(new BasicNameValuePair("name", "zhangsan")); //请求参数
httpPost.setEntity(new StringEntity("Hello, World")); /*
设置post请求参数
两个方式:具体参考UrlEncodedFormEntity和StringEntity区别
*/
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
//httpPost.setEntity(new StringEntity(list.toString(), "UTF-8")); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; //第三步 执行请求
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}

HttpClient HTTP Put请求

/**
* httpClient Put 请求
*/
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Post 请求 Url
HttpPut httpPut = new HttpPut("http://httpbin.org/put"); //设置post请求参数
httpPut.setEntity(new StringEntity("Hello, World")); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; String responseBody = httpclient.execute(httpPut, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} }

HttpClient HTTP Delete请求

/**
* httpClient Delete 请求
*/
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Delete 请求 Url
HttpDelete httpDelete = new HttpDelete("http://httpbin.org/delete"); System.out.println("Executing request " + httpDelete.getRequestLine()); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; String responseBody = httpclient.execute(httpDelete, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}

HttpClient自定义HTTP Header

/**
* HttpClient自定义HTTP头
*/
public static void main(String[] args)throws IOException {
// 创建自定义 http headers
List<Header> defaultHeaders = Arrays.asList(
new BasicHeader("X-Default-Header", "default header httpclient")); // 设置自定义 http headers
CloseableHttpClient httpclient = HttpClients
.custom()
.setDefaultHeaders(defaultHeaders)
.build(); try { // 配置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) //设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置请求超时时间
.setSocketTimeout(5000)
.setRedirectsEnabled(true)//默认允许自动重定向
.build(); // 创建自定义 http headers on the http request
HttpUriRequest request = RequestBuilder.get()
.setUri("http://httpbin.org/headers")
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.setHeader(HttpHeaders.FROM, "https://memorynotfound.com")
.setHeader("X-Custom-Header", "custom header http request")
.setConfig(requestConfig)
.build(); System.out.println("Executing request " + request.getRequestLine()); // 创建自定义 response handler
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(request, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}
}

更详细HttpClient 学习

教程参考:https://www.yiibai.com/httpclient/httpclient-overview.html (本文学习笔记)

Api参考:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/

github代码:https://github.com/YoCiyy/HttpClientDemo