Apache HttpComponents 之 Httpclie
2021-05-11 本文已影响0人
acc8226
Apache HttpComponents
Apache HttpComponents 项目负责创建和维护一个基于 HTTP 和相关协议的底层 Java 组件工具集。
官网地址 http://hc.apache.org/index.html
这里试图体验下 HttpClient 5.0 的用法
Apache Maven
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.0.3</version>
</dependency>
Gradle Groovy DSL
implementation 'org.apache.httpcomponents.client5:httpclient5:5.0.3'
Apache HttpComponents – HttpClient Quick Start
http get 和 http post 示例代码
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
}
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
}
}
文件上传 示例代码
package org.apache.hc.client5.http.examples;
import java.io.File;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
final FileBody bin = new FileBody(new File(args[0]));
final StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
final HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost);
try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
System.out.println("----------------------------------------");
System.out.println(response);
final HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
}
}
}
}
文件上传(并解决中文乱码 --- 进行 ISO-8859-1 编码)示例代码
// 包含了 对中文字符 的处理 FileBody 和 StringBody
private static void clientMultipartFormPost() throws IOException {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpPost httppost = new HttpPost("http://localhost:4000" + "/fileUpload");
File file = new File("D:/国徽面1.png");
String fileName = new String(file.getName().getBytes(), "ISO-8859-1");
final FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY, fileName);
final StringBody comment = new StringBody(new String("一种 binary 文件".getBytes(), "ISO-8859-1"), ContentType.TEXT_PLAIN);
final HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost);
try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
System.out.println("----------------------------------------");
System.out.println(response);
final HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
}
}
}
This example demonstrates how to send an HTTP request via a proxy (代理).
package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
/**
* How to send a request via proxy.
*
* @since 4.0
*/
public class ClientExecuteProxy {
public static void main(final String[] args)throws Exception {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpHost target = new HttpHost("https", "httpbin.org", 443);
final HttpHost proxy = new HttpHost("http", "127.0.0.1", 8080);
final RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
final HttpGet request = new HttpGet("/get");
request.setConfig(config);
System.out.println("Executing request " + request.getMethod() + " " + request.getUri() +
" via " + proxy);
try (final CloseableHttpResponse response = httpclient.execute(target, request)) {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
}