HttpClient修仙大典:从HTTP小厮到请求天尊的终极飞升指南

一、筑基篇:初识HttpClient

1.1 选择你的本命法宝

<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.13version>
dependency>


// 直接调用 java.net.http.HttpClient

二、金丹篇:基础HTTP请求

2.1 GET请求(灵气采集)
// Java 11+ 标准库版
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.example.com/data"))
        .GET()
        .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("状态码:" + response.statusCode());
System.out.println("响应体:" + response.body());
2.2 POST请求(灵力输送)
// 发送JSON数据(附赠护体结界)
String jsonBody = "{\"name\":\"张三\",\"age\":25}";

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.example.com/users"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
        .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

三、元婴篇:高级配置秘籍

3.1 超时设置(防渡劫超时)
HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5)) // 连接超时
        .followRedirects(HttpClient.Redirect.NORMAL) // 自动重定向
        .version(HttpClient.Version.HTTP_2) // 启用HTTP/2
        .build();
3.2 伪装大法(User-Agent伪装)
HttpRequest request = HttpRequest.newBuilder()
        .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)")
        .header("Accept-Language", "zh-CN,zh;q=0.9")
        .build();

四、化神篇:处理复杂场景

4.1 异步请求(分身渡劫术)
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .exceptionally(e -> {
            System.err.println("渡劫失败:" + e.getMessage());
            return null;
        });
// 主线程可继续执行其他任务
4.2 文件上传(乾坤大挪移)
// 构建multipart/form-data
String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
HttpRequest request = HttpRequest.newBuilder()
        .header("Content-Type", "multipart/form-data; boundary=" + boundary)
        .POST(ofMimeMultipartData(
            Map.of("name", "张三", "file", Path.of("report.pdf")), 
            boundary))
        .build();

// 需要自定义BodyPublisher(代码略长,建议封装工具类)

五、大乘篇:安全与异常处理

5.1 SSL证书信任(慎用!)
HttpClient client = HttpClient.newBuilder()
        .sslContext(insecureSSLContext()) // 自定义信任所有证书
        .build();

// 信任所有证书方法(测试环境专用!)
private static SSLContext insecureSSLContext() throws Exception {
    TrustManager[] trustAll = new TrustManager[]{new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
    }};
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAll, new SecureRandom());
    return sc;
}
5.2 异常处理(渡劫护体诀)
try {
    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
    if (response.statusCode() >= 400) {
        System.err.println("请求异常:" + response.body());
    }
} catch (IOException e) {
    System.err.println("IO异常:" + e.getMessage());
} catch (InterruptedException e) {
    System.err.println("请求中断:" + e.getMessage());
    Thread.currentThread().interrupt();
}

六、飞升篇:性能优化

6.1 连接池管理(节省灵力)
// Apache HttpClient配置
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200); // 最大连接数
cm.setDefaultMaxPerRoute(20); // 单路由最大连接

CloseableHttpClient client = HttpClients.custom()
        .setConnectionManager(cm)
        .build();
6.2 请求压缩(缩地成寸)
HttpRequest request = HttpRequest.newBuilder()
        .header("Accept-Encoding", "gzip, deflate") // 启用压缩
        .build();

// 自动解压响应(Java HttpClient默认支持)

渡劫成功总结

  1. 版本选择:旧项目用Apache版,Java 11+用标准库版
  2. 最佳实践:重用HttpClient实例、合理设置超时
  3. 安全守则:生产环境严格校验SSL证书
  4. 性能心法:连接池+异步请求+压缩传输

飞升后选择

  • 深度修炼:研究WebSocket/RESTful高级集成
  • 法宝升级:尝试OkHttp或Retrofit等现代库
  • 跨界融合:整合到Spring生态的RestTemplate

你可能感兴趣的:(业务系统应用技术,http,网络协议,网络)