Why does Retrofit make an exception when the status code is 204?

Asked

Viewed 176 times

1

After a consultation GET only to check if a content exists on the server, the return is 200 (exists) or 204 (there is no).

Why does Retrofit trigger the exception below when the server returns the Status Code: 204 No Content?

java.net.Protocolexception: HTTP 204 had non-zero Content-Length: 37

Using Postman, for example, makes no mistake.

1 answer

3


In class okhttp3.internal.http.HttpEngine, in the method Response proceed(Request request) there is the following:

  Response var6 = HttpEngine.this.readNetworkResponse();
  int var9 = var6.code();
  if((var9 == 204 || var9 == 205) && var6.body().contentLength() > 0L) {
    throw new ProtocolException("HTTP " + var9 + " had non-zero Content-Length: " + var6.body().contentLength());
  } else {
     return var6;
  }

So if it returns 204 or 205 And contentLength of body is greater than 0,

will pop a ProtocolException

In your case, you’re returning 204 and your contentLength is 37 !

You can intercept a ProtocolException and treat this situation:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(new Interceptor() {
  @Override
  public Response intercept(Chain chain) throws IOException {
      Response response;
      try {
        response = chain.proceed(chain.request());
      } catch (ProtocolException e) {
        response = new Response.Builder()
            .request(chain.request())
            .code(204)
            .protocol(Protocol.HTTP_1_1)
            .build();
      }
    return response;
  }
});

But this may cause more problems, because it is not only in this context that this Exception.

  • 1

    That’s right. I took a look at the class and saw, but I waited for someone to answer. The server was returning content when it was not to return.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.