Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement receiving a server push in OkHttp?

Following the question Does OkHttp support HTTP/2 server push?, are there any examples available on how receiving pushed content on the client side could be implemented?

How will the interaction of OkHttpClient, Request, Response and Http2Connection be? I understand that the Http2Connection has a PushObserver, but how will it play together with OkHttpClient and Request/Response?

Consider the snippet below. There is a client and a request. How would they come together with the PushObserver?

    OkHttpClient client = getOkHttpClient();
    Request request = new Request.Builder()
            .url("https://nghttp2.org:443") // The Http2Server should be running here.
            .build();
    try {
        Socket socket = client.socketFactory().createSocket();
        Http2Connection con = new Http2Connection.Builder(true)
            .socket(socket)
            .pushObserver(new PushObserver(){

            @Override
            public boolean onRequest(int streamId, List<Header> requestHeaders) {
                // do something here
                return true;
            }

            @Override
            public boolean onHeaders(int streamId,
                List<Header> responseHeaders, boolean last) {
                // do something here
                return true;
            }

            @Override
            public boolean onData(int streamId, BufferedSource source,
                int byteCount, boolean last) throws IOException {
                // do something here
                return true;
            }

            @Override
            public void onReset(int streamId, ErrorCode errorCode) {
                // do something
            }
        }).build();

    } catch (IOException e) {
        LOG.error("IOException", e);
    }
like image 575
Erunafailaro Avatar asked Oct 17 '22 20:10

Erunafailaro


1 Answers

OkHttp has no public APIs for server push and it is unlikely to gain them. We’re building mechanisms to persist pushed responses into the cache, but it’s unlikely this will be visible to application code. You just get a faster response sometimes because the server pushed it into the cache.

If you need this kind of behavior please look at web sockets.

like image 103
Jesse Wilson Avatar answered Oct 21 '22 00:10

Jesse Wilson