android - 如何使用 Retrofit 在 JSON 请求中获取 "nameValuePairs"?

标签 android json retrofit2

如何发布如下所示的 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接口(interface):

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

主要 Activity 代码:

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 使用相同的请求。

最佳答案

更改您的 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));
                }
            });

        }

For more details check this answer suggested by 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))
        }
    })
}

关于android - 如何使用 Retrofit 在 JSON 请求中获取 "nameValuePairs"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015786/

相关文章:

android - 用于改造响应代码处理的自定义 rx Func1

android - 如何处理 Retrofit 2 中可能不同类型的响应

php - 我如何使用改造上传多个文件

java - 尝试..捕获场景

java - 在 ListView 元素内绘制到 Canvas

android - 我可以在 android 的 id 属性中使用冒号吗?

json - 如何展开 JSON 对象?

java - 如何将有序数据放入jsonObject中?

php - PHP中的增量JSON解析

javascript - 如何将输入文件对象序列化为 JSON?