Okhttp: Always return response content length is -1

Created on 25 Apr 2017  Â·  4Comments  Â·  Source: square/okhttp

I tried with a lot of different urls but always response content length is -1

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

Request request = new Request.Builder()
                .addHeader("Referer", "http://www.google.com")
                .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Firefox/52.0")
                .addHeader("Connection", "keep-alive");
                .url(url).build();
Response response = client.newCall(request).execute();

boolean isSuccessful = response.isSuccessful();
int contentLength = response.body().contentLength();

Response return 200 code but contentLength is equal -1 and isSuccessful is true. I dont know what should I do? I tried 20 different urls but result is same.

NOTES:

  • I use emulator.
  • gradles >> classpath 'com.android.tools.build:gradle:2.3.1' and compile 'com.squareup.okhttp3:okhttp:3.7.0'

Most helpful comment

Correct. It just means that the length isn't known and must be streamed.

All 4 comments

A content length of -1 means unknown. You can still call .string() or .bytes() or stream the body with .source(). This is usually because of transparent gzip which prevents us from knowing the actual body length.

@JakeWharton you are right. I debugged responseBody.string() is success. So it means there is no problem with my code?

Correct. It just means that the length isn't known and must be streamed.

@JakeWharton thanks a lot. you saved my time

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dannyZhou picture dannyZhou  Â·  3Comments

vanshg picture vanshg  Â·  3Comments

HyakYegoryaln picture HyakYegoryaln  Â·  3Comments

SandroMachado picture SandroMachado  Â·  3Comments

GuiForget picture GuiForget  Â·  3Comments