How to read body following an 101 response code?

落爺英雄遲暮 提交于 2019-12-11 17:56:11

问题


From the docs,

immediately after sending the 101 (Switching Protocols) response, the server is expected to continue responding to the original request as if it had received its equivalent within the new protocol (i.e., the server still has an outstanding request to satisfy after the protocol has been changed, and is expected to do so without requiring the request to be repeated).

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

I have made my interceptors(Using OkHttp) as follows

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.
    }
    upgradeResponse.body(); // returns null
    // I am clueless on how to read the response hereafter.
    // As per the docs, the 101 status code reply will be followed by a data stream. How can I access this?
    return upgradeResponse;

}

}

So basically, for a single request. I will receive 101 as response first if the upgrade is successful, then followed by another response as per the upgraded protocol(if my understanding is right?). Is there anyway to achieve this with OkHttp? Or, Any other client also would be helpful.

Thanks!

来源:https://stackoverflow.com/questions/58170331/how-to-read-body-following-an-101-response-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!