Okhttp java.net.ProtocolException: unexpected end of stream

Question:

im currently working on Android aplication and im making a simple GET request using okttp3. Im using my flask aplication as the API endpoint.
Code Android:

 OkHttpClient client = new OkHttpClient();

        final Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                    String s = response.body().string();
                    System.out.println(s);

            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

                System.out.println(e.getMessage());
            }

        });

Code Flask

@app.route('/abc', methods=["GET"])
def abc():
    return jsonify({"test": "abc"})

When i make the request using POSTMAN i have no issues:
postman get request
However when using the java code above sometimes it works, other times i get the following error

D/OkHttp: java.net.ProtocolException: unexpected end of stream
        at okhttp3.internal.http1.Http1ExchangeCodec$FixedLengthSource.read(Http1ExchangeCodec.kt:389)
        at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:276)
        at okio.Buffer.writeAll(Buffer.kt:1655)
        at okio.RealBufferedSource.readString(RealBufferedSource.kt:95)
        at okhttp3.ResponseBody.string(ResponseBody.kt:187)
        at com.example.teste.MainActivity$2.onResponse(MainActivity.java:83)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
D/OkHttp:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

I have tried mutiple solutions that have been sugested at other posts like:

OkHttpClient client = new OkHttpClient.Builder()
    .retryOnConnectionFailure(true)
    .build();

or

Request request = new Request.Builder()
                    .addHeader("Authorization", "Bearer " + apiToken)
                    .addHeader("content-type", "application/json")
                    .addHeader("Connection","close")
                    .url(uri)
                    .build();

but none of them work. Whats the problem here? I have tried making requests with the same code with other dummy api and it always works. What is my flask api missing?

The error happens here:

val read = super.read(sink, minOf(bytesRemaining, byteCount))
      if (read == -1L) {
        connection.noNewExchanges() // The server didn't supply the promised content length.
        val e = ProtocolException("unexpected end of stream")
        responseBodyComplete()
        throw e
      }

It has something to do with the content lenght supplied by the server. How do i solve this?

Asked By: acG

||

Answers:

what about adding an interceptor for each request and add Connection-Close header? as below.

okHttpClient = new OkHttpClient.Builder()
        .addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("Connection", "close").build();
                return chain.proceed(request);
            }
        })
        .build();

HTTP/1.1 defines the “close” connection option for the sender to signal that the connection will be closed after completion of the
response. For example,

Connection: close in either the request or the response header
fields indicates that the connection SHOULD NOT be considered
`persistent’ (section 8.1) after the current request/response is
complete.

HTTP/1.1 applications that do not support persistent connections MUST
include the “close” connection option in every message.

The exception was only happening when i use the emulator. On the device there was no problem.

Answered By: acG

I’m writing a proxy-server which does request body adjustments. So I changed body but forgot to adjust Content-Length=123 header and HTTPClient was getting this error. So it might mean inconsistency between this header and actual body length.

Answered By: Dmitriy Krendelev
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.