Okhttp: Android warning response.body().string();

Created on 1 Oct 2017  Â·  6Comments  Â·  Source: square/okhttp

Hello.

I am getting this warning in this code: myString = response0.body().string();

Method invocation 'string' may produce 'java.lang.NullPointerException'

The problem appears in string(). This code is inside try-catch.

How can I solve this safety? I searched in StackOverflow but I found nothing.

The app is working perfectly, it is just a warning.

Most helpful comment

The warning can be suppressed for a normal response. The body is only null for a cached response or network response.

All 6 comments

The warning can be suppressed for a normal response. The body is only null for a cached response or network response.

Well I didn't read the second part @jakewharton. It is a network response

Then it will always be null.

On Sun, Oct 1, 2017, 1:39 PM Javier Segovia Córdoba <
[email protected]> wrote:

Reopened #3635 https://github.com/square/okhttp/issues/3635.

—
You are receiving this because you were mentioned.

Reply to this email directly, view it on GitHub
https://github.com/square/okhttp/issues/3635#event-1273145246, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AAEEEZyAdX2hteQiseUVA_RPn5JELpavks5sn85mgaJpZM4Pp6FZ
.

Sorry @JakeWharton, I am not understanding you:

client = new OkHttpClient();
request = new Request.Builder().url(url).build();
response = client.newCall(request).execute();
myString = response.body().string();

This is working in my app, is it a network response? It is not null, the response is giving me a JSON.

response.body() may be null in 3 of 4 cases. There is the top level response you are using and it's safe to call body().string on it. But there are the other accessors at well which mean the method has to be marked as @Nullable.

Hence the compiler doesn't know that your response.body() is guaranteed to be non-null.

You code is safe, but you will need to ignore this warning, or add a useless null check.

Response.java

  /**
   * Returns a non-null value if this response was passed to {@link Callback#onResponse} or returned
   * from {@link Call#execute()}. Response bodies must be {@linkplain ResponseBody closed} and may
   * be consumed only once.
   *
   * <p>This always returns null on responses returned from {@link #cacheResponse}, {@link
   * #networkResponse}, and {@link #priorResponse()}.
   */
  public @Nullable ResponseBody body() {
    return body;
  }

  /**
   * Returns the raw response received from the network. Will be null if this response didn't use
   * the network, such as when the response is fully cached. The body of the returned response
   * should not be read.
   */
  public @Nullable Response networkResponse() {
    return networkResponse;
  }

  /**
   * Returns the raw response received from the cache. Will be null if this response didn't use the
   * cache. For conditional get requests the cache response and network response may both be
   * non-null. The body of the returned response should not be read.
   */
  public @Nullable Response cacheResponse() {
    return cacheResponse;
  }

  /**
   * Returns the response for the HTTP redirect or authorization challenge that triggered this
   * response, or null if this response wasn't triggered by an automatic retry. The body of the
   * returned response should not be read because it has already been consumed by the redirecting
   * client.
   */
  public @Nullable Response priorResponse() {
    return priorResponse;
  }

replace response.body().string() with String successResponse = new Gson().toJson(response.body());

full code:

call.enqueue(new Callback<Object>() {
        @Override
        public void onResponse(@NonNull Call<Object> call, @NonNull Response<Object> response) {
            if (response.isSuccessful()) {
                Gson gson = new Gson();
                String successResponse = gson.toJson(response.body());
                Log.d(LOG_TAG, "successResponse: " + successResponse);
            } else {
                try {
                    if (null != response.errorBody()) {
                        String errorResponse = response.errorBody().string();
                        Log.d(LOG_TAG, "errorResponse: " + errorResponse);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(@NonNull Call<Object> call, @NonNull Throwable t) {
        }
    });

Was this page helpful?
0 / 5 - 0 ratings