0

I want to use retrofit for fetching data from my server. My server send data as a string json. I create a server like this:

public class ServiceGenerator {

    public static final String BASE_URL = "http://192.168.100.73/ChartReport/Service1.svc/";


    static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(1, TimeUnit.MINUTES)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .build();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create());

    private static Retrofit retrofit = builder.build();

    public static <S> S createService(Class<S> serviceClass) {
        return retrofit.create(serviceClass);
    }
}

And then i have created client like blow:

public interface IReportCLient {
    @POST("json/GetDataReport")
    Call<ResponseBody> getReporst();
}

And I have used into my activity :

IReportCLient service = ServiceGenerator.createService(IReportCLient.class);
Call<ResponseBody> reporst = service.getReporst();

reporst.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            JsonObject post = new JsonObject().get(response.body().string()).getAsJsonObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {

    }
});

When I run my app in debug mode for first time i fetch my data by this command: response.body().string() but immediately my result is null when i run response.body().string() again?? enter image description here

What is happens?

Cyrus the Great
  • 5,145
  • 5
  • 68
  • 149

1 Answers1

1

string() method can only be called once on RequestBody. So it will return empty string if you try to call it again. This is true for debugging as well. If you try to evaluate expressions response.body().string() while debugging, your actual methods will get empty string.

An HTTP response. Instances of this class are not immutable: the response body is a one-shot value that may be consumed only once and then closed. All other properties are immutable. https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html

Read this as well https://stackoverflow.com/a/32307866/6168272

This is how I get JsonObject from my response object. You can give it a try.

private JSONObject parseJsonFromResponse(Response response) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                try {
                    return new JSONObject(responseBody.string());
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                    return new JSONObject();
                }
            } else return new JSONObject();
        }
Ranjan
  • 1,096
  • 10
  • 22
  • In any case if i not use debugging mode, i got error on `new JsonObject().get(response.body().string()).getAsJsonObject();` i got `java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.gson.JsonObject com.google.gson.JsonElement.getAsJsonObject()' on a null object reference` – Cyrus the Great Jun 30 '18 at 13:01
  • That means you `JsonObject` is null because `JsonObject().get(responseBody)` returned null. – Ranjan Jun 30 '18 at 13:03
  • Of course but for a little time it is not .. you casn see in picture that i sended – Cyrus the Great Jun 30 '18 at 13:04
  • `response.body().string()` is not null, your `JsonObject().get()` method couldn't parse or something and returned a null object. – Ranjan Jun 30 '18 at 13:05
  • You can modify the else part. I needed an empty `JSONObject`. – Ranjan Jun 30 '18 at 13:07
  • I try your code :`public void onResponse(Call call, Response response) { JSONObject jsonObject = parseErrorJsonFromResponse(response); Log.i("======>", "onResponse: " + jsonObject.toString()); }` this is logcat output: `.com.chartreport I/======>: onResponse: {}` – Cyrus the Great Jun 30 '18 at 13:11
  • Actually, you have to use `response.body()` instead of `response.errorBody()` in my code. – Ranjan Jun 30 '18 at 14:29
  • You saved my life :) Thank you ... You are rockstar ...I was breaking my head for 2 days to fix this...... – Grace Venkat Jul 02 '19 at 07:01