JDK17 Http Request 异步处理 源码刨析

为什么可以异步?

#调用起始源码

// 3. 发送异步请求并处理响应

CompletableFuture future = client.sendAsync(

request,

HttpResponse.BodyHandlers.ofString() // 响应体转为字符串

).thenApply(response -> {

// 状态码检查(非200系列抛出异常)

if (response.statusCode() < 200 || response.statusCode() >= 300) {

throw new RuntimeException("HTTP错误: " + response.statusCode());

}

return response;

}).thenApply(HttpResponse::body) // 提取响应体3

.thenAccept(body -> {

// 4. 打印响应结果(截取前100字符示例)

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

System.out.println("\n▼ 响应内容 (前100字符):\n"

  • body.substring(0, Math.min(100, body.length())) + "...");

}).exceptionally(e -> {

// 5. 异常处理(提取根本原因)

Throwable root = e;

while (root.getCause() != null) root = root.getCause();

System.err.println("❌ 请求失败: " + root.getMessage());

return null;

});

#client.sendAsync

复制代码
public CompletableFuture<T> whenComplete(
    BiConsumer<? super T, ? super Throwable> action) {
    return uniWhenCompleteStage(null, action);
}

@Override

public CompletableFuture<HttpResponse>

sendAsync(HttpRequest userRequest, BodyHandler responseHandler)

{

return sendAsync(userRequest, responseHandler, null);

}

复制代码
@Override
public <T> CompletableFuture<HttpResponse<T>>
sendAsync(HttpRequest userRequest,
          BodyHandler<T> responseHandler,
          PushPromiseHandler<T> pushPromiseHandler) {
    return sendAsync(userRequest, responseHandler, pushPromiseHandler, delegatingExecutor.delegate);
}

#关键在这里

@SuppressWarnings("removal")

private CompletableFuture<HttpResponse>

sendAsync(HttpRequest userRequest,

BodyHandler responseHandler,

PushPromiseHandler pushPromiseHandler,

Executor exchangeExecutor) {

复制代码
    Objects.requireNonNull(userRequest);
    Objects.requireNonNull(responseHandler);



        MultiExchange<T> mex = new MultiExchange<>(userRequest,
                                                        requestImpl,
                                                        this,
                                                        responseHandler,
                                                        pushPromiseHandler,
                                                        acc);
        CompletableFuture<HttpResponse<T>> res =
                mex.responseAsync(executor).whenComplete((b,t) -> unreference());
        if (DEBUGELAPSED) {
            res = res.whenComplete(
                    (b,t) -> debugCompleted("ClientImpl (async)", start, userRequest));
        }
相关推荐
百锦再7 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
吠品7 小时前
企业信任基石OV SSL证书
网络协议·https·ssl
2501_916008898 小时前
全面介绍Fiddler、Wireshark、HttpWatch、SmartSniff和firebug抓包工具功能与使用
android·ios·小程序·https·uni-app·iphone·webview
暖馒8 小时前
Modbus应用层协议的深度剖析
网络·网络协议·c#·wpf·智能硬件
玉梅小洋9 小时前
Windows 10 Android 构建配置指南
android·windows
开源技术9 小时前
DNS详解——域名是如何解析的
http
Libraeking10 小时前
视觉篇:Canvas 自定义绘图与高级动画的华丽圆舞曲
android·经验分享·android jetpack
Fushize11 小时前
多模块架构下的依赖治理:如何避免 Gradle 依赖地狱
android·架构·kotlin
Jomurphys11 小时前
Kotlin - 类型别名 typealias
android·kotlin
Haha_bj12 小时前
Flutter ——flutter_screenutil 屏幕适配
android·ios