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

414
May 17, 2017, at 2:34 PM

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.

Answer 1

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 .

Rent Charter Buses Company
READ ALSO
Android Studio 2.3 AVD Manager Greyed out?

Android Studio 2.3 AVD Manager Greyed out?

I just recently installed Android Studio (Version 23) so I could use the SDK / AVD GUI manager built in now that the standalone is deprecated

677
Is it possible to pass Interface reference to fragment from view holder?

Is it possible to pass Interface reference to fragment from view holder?

Fragment added inside row item from viewholder how to update viewholder directly from fragment?

220
With Microsoft Band 2, can I save the collected health data and send to mobile when connected with Bluetooth?

With Microsoft Band 2, can I save the collected health data and send to mobile when connected with Bluetooth?

What I'm going to do is to collect heartbeat rate, RR interval, Acceleration, and the time when worn and send them to an Android phone when they are connected to each other with Bluetooth

281