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

1

After a GET query only to check if a content exists on the server, the return is 200 (exists) or 204 (does not exist).

Why does Retrofit throw the exception below when the server returns the Status Code: 204 In Content ?

  

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

Using Postman, for example, does not give any error.

    
asked by anonymous 08.03.2017 / 21:39

1 answer

2

In the okhttp3.internal.http.HttpEngine class, in the Response proceed(Request request) method 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 you return 204 or 205 And contentLength of body is greater than 0 ,

will pop a ProtocolException

In your case, you are 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 can lead to more problems, because it is not only in this context that this Exception is thrown.

    
08.03.2017 / 22:55