gpt4 book ai didi

java - okHttp拦截器中的协议(protocol)升级机制

转载 作者:行者123 更新时间:2023-12-02 00:04:32 24 4
gpt4 key购买 nike

我需要将我的请求从 HTTP1.1 服务升级到 HTTP/2。到目前为止,这是我尝试过的。

public class H2cUpgradeRequestInterceptor implements Interceptor {
private static final Log logger = LogFactory.getLog(H2cUpgradeRequestInterceptor.class);

@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request upgradeRequest = request.newBuilder().addHeader("Connection", "Upgrade, HTTP2-Settings")
.addHeader("Upgrade", "h2c").addHeader("HTTP2-Settings", "AAMAAABkAARAAAAAAAIAAAAA").build();
Response upgradeResponse = chain.proceed(upgradeRequest);
if (upgradeResponse != null && upgradeResponse.code() == HttpStatus.SC_SWITCHING_PROTOCOLS) {
logger.debug("Switching Protocols success"); // Success. Got 101 in reply.
}
Response response = chain.proceed(request);
if (response.protocol() == Protocol.HTTP_2) { // This is returning HTTP1.1 as protocol
logger.debug("Used upgraded h2c protocol");
}
return response;

}

}

我的服务器启用了 h2c。我还在第一次 chain.proceed() 调用中收到了 101 个切换协议(protocol)。但即使切换协议(protocol)成功,下一个 proceed() 总是给我 HTTP1.1 作为协议(protocol)。这是实现协议(protocol)升级的正确方法吗?如果是,如何确保切换协议(protocol)成功后使用的是HTTP2?

最佳答案

自此结束,根据 docs

我不需要再次发送请求。

If the Upgrade header field is received in a GET request and theserver decides to switch protocols, it first responds with a 101(Switching Protocols) message in HTTP/1.1 and then immediately followsthat with the new protocol's equivalent of a response to a GET on thetarget resource. This allows a connection to be upgraded to protocolswith the same semantics as HTTP without the latency cost of anadditional round trip.

关注here

关于java - okHttp拦截器中的协议(protocol)升级机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58163115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com