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

安稳与你 提交于 2020-01-29 09:23:06

问题


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.


回答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 .



来源:https://stackoverflow.com/questions/44015786/how-do-i-get-namevaluepairs-in-a-json-request-using-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!