【问题标题】:How do I get "nameValuePairs" in a JSON request using Retrofit?如何使用 Retrofit 在 JSON 请求中获取“nameValuePairs”?
【发布时间】:2017-05-17 04:43:57
【问题描述】:

我如何发布如下JSONObject 请求?

原始请求:

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

在 Volley 中,我可以成功发布JSONObject 请求。但是当我在 Retrofit 中使用它时,我的请求更改如下:

我在日志中得到了什么:

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

我收到来自服务器端的错误请求。

我用于改造的 API 接口:

public interface ApiInterface {

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

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

我的 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 代码:

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));
        }
    });

}

注意:我也尝试使用HashMap,但自动添加了相同的nameValuePairs 参数。如果我使用 Gson JsonObject 然后请求序列化转换。因此,我不想在服务器端进行任何更改,因为使用 Volley 可以正常工作。但是现在我想使用相同的请求来使用 Retrofit。

【问题讨论】:

标签: android json retrofit2


【解决方案1】:

更改 My APi 接口以进行改造

public interface ApiInterface {

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


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

也像这样更改 Mainactivity 代码

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));
                }
            });

        }

有关更多详细信息,请查看此 answer 建议 Pratik Vyas .



在 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))
        }
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多