Search code examples
androidjsonretrofit2

How do I get "nameValuePairs" in a JSON request using Retrofit?


How do I post post a JSONObject request like below?

Original REQUEST:

    {
        "pObj": [],
        "robj": [
            {
                "l_index": "1",
                "user_id": "111",
                "vername": "1",
                "fcmtoken": "ghkghkhkh"
            }
        ],
        "uobject": [],
        "pname": "y6y68uuy7"
    }

In Volley I can successfully post JSONObject request. But when I am using this in Retrofit my request is changed as below:

What I am get in log:

  {
        "nameValuePairs": {
            "pObj": {
                "values": []
            },
            "robj": {
                "values": [
                    {
                        "nameValuePairs": {
                            "l_index": "1",
                            "user_id": "111",
                            "vername": "1",
                            "fcmtoken": "ghkghkhkh"
                        }
                    }
                ]
            },
            "uobject": {
                "values": []
            },
                    "pname": "y6y68uuy7"
        }
    }

And I am getting bad request from server side.

My API Interface for Retrofit:

public interface ApiInterface {

    @Headers( "Content-Type: application/json; charset=utf-8")
    @POST("re_clientdata")

    Call<String> savePost(@Body JSONObject  req);
}

My APIClient

public class ApiClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor).build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

MainActivity code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sendPost(jRequest);
}

public void sendPost(JSONObject requestobject) {
    Log.e("requestobject",requestobject.toString());

    Call<String> call =mAPIService.savePost(requestobject);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String>callback,Response<String>response) {
            String res = response.body();
            Log.e("DEMO", "post submitted to API." + response);
        }
        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.e("DEMO", "Unable to submit post to API.",t);
            Log.e("call", String.valueOf(call));
        }
    });

}

Note: I also tried using HashMap but same nameValuePairs parameter added automatically. And If I use Gson JsonObject then request convert in serialize. So I don't want to any change in server side cause it's works fine using Volley. But now I want to use Retrofit using same request.


Solution

  • Change In your My APi Interface for Retrofit

    public interface ApiInterface {
    
        @Headers( "Content-Type: application/json; charset=utf-8")
        @POST("re_clientdata")
    
    
        Call<String> savePost(@Body RequestBody req);
    }
    

    Also change Mainactivity code like this

    protected void onCreate(Bundle savedInstanceState) {
            
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    
                     sendPost(jRequest);
        
            }
    
            public void sendPost(JSONObject requestobject) {
                Log.e("requestobject",requestobject.toString());
               
                  RequestBody myreqbody = null;
                    try {
                         myreqbody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                                (new JSONObject(String.valueOf(requestobject))).toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
                    Call<String> call =mAPIService.savePost(myreqbody);
    
    
                call.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String>callback,Response<String>response) {
                        String res = response.body();
                        Log.e("DEMO", "post submitted to API." + response);
                    }
                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        Log.e("DEMO", "Unable to submit post to API.",t);
                        Log.e("call", String.valueOf(call));
                    }
                });
    
            }
    

    For more details check this answer suggested by Pratik Vyas .



    In kotlin

    fun sendPost(requestobject: JSONObject) {
        Log.e("requestobject", requestobject.toString())
        var myreqbody: RequestBody? = null
        try {
            myreqbody = JSONObject(requestobject.toString()).toString()
                .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val call: Call<String> = mAPIService.savePost(myreqbody)
        call.enqueue(object : Callback<String?>() {
            fun onResponse(callback: Call<String?>?, response: Response<String?>) {
                val res: String = response.body()
                Log.e("DEMO", "post submitted to API.$response")
            }
    
            fun onFailure(call: Call<String?>?, t: Throwable?) {
                Log.e("DEMO", "Unable to submit post to API.", t)
                Log.e("call", java.lang.String.valueOf(call))
            }
        })
    }