Apache HttpComponents 之 Httpclient 参考

简介: Apache HttpComponentsApache HttpComponents 项目负责创建和维护一个基于 HTTP 和相关协议的底层 Java 组件工具集。

Apache HttpComponents


Apache HttpComponents 项目负责创建和维护一个基于 HTTP 和相关协议的底层 Java 组件工具集。


官网地址 http://hc.apache.org/index.html


image.png


这里试图体验下 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()));
            }
        }
    }
}




目录
相关文章
|
Java Apache Maven
Sentinel Apache Httpclient 适配器介绍
Sentinel 为 OkHttp 客户端提供集成以启用 Web 请求的流量控制。
|
7月前
|
数据采集 机器学习/深度学习 Java
数据猎手:使用Java和Apache HttpComponents库下载Facebook图像
本文介绍了如何使用Java和Apache HttpComponents库从Facebook获取图像数据。通过设置爬虫代理IP以避免限制,利用HttpClient发送请求,解析HTML找到图像链接,然后下载并保存图片。提供的Java代码示例展示了实现过程,包括创建代理配置、线程池,以及下载图片的逻辑。注意,实际应用需根据Facebook页面结构进行调整。
数据猎手:使用Java和Apache HttpComponents库下载Facebook图像
|
6月前
|
JSON 前端开发 API
Apache HttpClient调用Spring3 MVC Restful Web API演示
Apache HttpClient调用Spring3 MVC Restful Web API演示
54 1
|
7月前
|
JSON Java Apache
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
431 0
|
7月前
|
数据采集 前端开发 Java
利用Scala与Apache HttpClient实现网络音频流的抓取
利用Scala与Apache HttpClient实现网络音频流的抓取
|
7月前
|
数据采集 安全 Java
Kotlin+Apache HttpClient+代理服务器=高效的eBay图片爬虫
本文将为你介绍一种高效的eBay图片爬虫的实现方式,让你可以用Kotlin+Apache HttpClient+代理服务器的组合来轻松地下载eBay的图片。
100 1
Kotlin+Apache HttpClient+代理服务器=高效的eBay图片爬虫
|
7月前
|
Java Apache
Apache HttpClient 4.5设置超时时间
Apache HttpClient 4.5设置超时时间
266 0
|
Arthas Java 测试技术
一次NSF FeignClient支持Apache HttpClient的优化
一次NSF FeignClient支持Apache HttpClient的优化
304 2

推荐镜像

更多