1

I am trying to make a newtwork request using Retrofit 2. From the log, i can see that i am receiving response from server and the correct results. But at onResponse body i cannot parse response.

I receive exception at

JSONObject jsonObject = new JSONObject(response.body().toString());

In my php file i did add header

header('Content-type=application/json; charset=utf-8');

And i return my response using method below

echo json_encode($RETURN_DATA,JSON_FORCE_OBJECT);

But in logcat, i see my response is not same with my header

Content-Type: text/html; charset=UTF-8

My code:

public void login(View view) {
    mApiService.loginRequest(input_username.getText().toString(), MD5.getMd5(input_password.getText().toString()))
            .enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if(response.isSuccessful()){
                        //Loading dismiss
                        //Logger.getLogger().d(String.valueOf(response.code()), Logger.LOGGER_DEPTH.ACTUAL_METHOD);
                        //Logger.getLogger().d(String.valueOf(response.body()), Logger.LOGGER_DEPTH.ACTUAL_METHOD);

                        try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());

                            } catch (JSONException e) {
                                // e.printStackTrace();
                                Logger.getLogger().d(e.toString(), Logger.LOGGER_DEPTH.ACTUAL_METHOD);

                            }
                    }else{
                        //Loading dismiss
                        Logger.getLogger().d(String.valueOf(response.code()), Logger.LOGGER_DEPTH.ACTUAL_METHOD);

                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    //Loading dismiss
                    Logger.getLogger().d(String.valueOf(call.isCanceled()),t, Logger.LOGGER_DEPTH.ACTUAL_METHOD);
                }
            });
}

This is from my logcat

05-23 06:18:46.011 7889-7963/com.example.myapplication D/OkHttp: <-- 200 OK http://192.168.56.1/AndroidServer/login.php (301ms)
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: Date: Thu, 23 May 2019 06:18:46 GMT
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: Server: Apache/2.4.37 (Win32) OpenSSL/1.1.1a PHP/7.2.13
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: X-Powered-By: PHP/7.2.13
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: Content-Length: 64
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: Keep-Alive: timeout=5, max=100
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: Connection: Keep-Alive
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: Content-Type: text/html; charset=UTF-8
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: {"TITLE":"Authentication Successful","MESSAGE":"Welcome Back !"}
05-23 06:18:46.012 7889-7963/com.example.myapplication D/OkHttp: <-- END HTTP (64-byte body)
05-23 06:18:46.023 7889-7889/com.example.myapplication D/ActivityLogin$1[onResponse] - 61: okhttp3.ResponseBody$Companion$create$1@25aa0e1c
05-23 06:18:46.024 7889-7889/com.example.myapplication D/ActivityLogin$1[onResponse] - 85: org.json.JSONException: Value okhttp3.ResponseBody$Companion$create$1@25aa0e1c of type java.lang.String cannot be converted to JSONObject
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
KIRPAL SINGH
  • 185
  • 2
  • 17

3 Answers3

1

First of all you should create a class about your response for map your response to it.

Then use Gson for convert JSON to Java objects(Your object), like this :

Add Gson to your gradle :

implementation 'com.google.code.gson:gson:2.8.5'

And in your activity or fragment :

Gson gson = new Gson();
YourResponseClass object = new YourResponseClass();
object = gson.fromJson(response.body().toString(), YourResponseClass.class);

Read more about Gson at this

milad salimi
  • 1,580
  • 2
  • 12
  • 31
1

I dont know why but this somehow solved my question. I saw solution in the link below. Instead of using

JSONObject jsonObject = new JSONObject(response.body().string());

My reference: How does OkHttp get Json string?

Perhaps someone can clarify why .toString doesnt work?

KIRPAL SINGH
  • 185
  • 2
  • 17
0

Try to use Gson library. Include in project: https://mvnrepository.com/artifact/com.google.code.gson/gson/2.7

Instead of JSONObject jsonObject = new JSONObject(response.body().toString()); use Gson().fromJson(yourResponse, Example.class);
In order to do this, declare new class, like:

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("TITLE")
@Expose
private String tITLE;
@SerializedName("MESSAGE")
@Expose
private String mESSAGE;

public String getTITLE() {
return tITLE;
}

public void setTITLE(String tITLE) {
this.tITLE = tITLE;
}

public String getMESSAGE() {
return mESSAGE;
}

public void setMESSAGE(String mESSAGE) {
this.mESSAGE = mESSAGE;
}

}

BTW, if you are curious, how I made this class so easy, you can go to that link: http://www.jsonschema2pojo.org/

samaromku
  • 560
  • 2
  • 7