【问题标题】:How do I delete “nameValuePairs” in a JSON request using Retrofit?如何使用 Retrofit 删除 JSON 请求中的“nameValuePairs”?
【发布时间】:2019-02-22 09:21:10
【问题描述】:

我正在尝试在 POST 请求中发送原始数据,但 nameValuePairs 键与我的 JSON 连接在一起。

这是我的请求方法:-

@Headers( "Content-Type: application/json; charset=utf-8")
    @POST("mpapi/seller/sellerprofilepost")
    Call<ResponseBody>
    updateProfile(@Header("Authorization") String token,
                  @Body JSONObject body);

我正在发送这个:-

{
    "firstname": "test1ff"
}

但在后端他们正在接收:-

{
    "nameValuePairs":
    {
        "firstname":"test1ff"

    }
}

api调用方法:-

private void updateProfile() {
        try {
            showLoader();
            JSONObject obj=new JSONObject();
            obj.put("firstname",first_name.getText().toString().trim());
            call = api.updateProfile("Bearer k8yu1q0k790lw5y4ta49alfbtsxoxs1w",obj);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        if (response.isSuccessful()) {
                            JSONObject obj = new JSONObject(response.body().string());
                            dialog = Func.OneButtonDialog(mContext, obj.getString("message"), ProfileScreen.this);
                        } else {
                            JSONObject obj = new JSONObject(response.errorBody().string());
                            dialog = Func.OneButtonDialog(mContext, obj.getString("message"), ProfileScreen.this);
                        }
                    } catch (Exception e) {
                        dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), ProfileScreen.this);
                        e.printStackTrace();
                    }
                    hideLoader();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), ProfileScreen.this);
                    hideLoader();
                }
            });
        } catch (Exception e) {
            dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), this);
            hideLoader();
            e.printStackTrace();
        }
    }

改造调用方法:- 这是我设置基本 url、标题等的改造调用方法

public Retrofit retrofitCall() {
        String baseUrl = Constants.baseURL;
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(getSSLSocketFactory())
                .retryOnConnectionFailure(true)
                .addInterceptor(new AddHeaderInterceptor())
                .readTimeout(40, TimeUnit.SECONDS)
                .connectTimeout(40, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }

【问题讨论】:

  • 请添加一些代码
  • 添加调用 updateProfile() 方法的代码。
  • 不使用android的JSONObject,而是使用GSON的JsonObject,通过addProperty(String property, Value)方法构造对象
  • 代替obj.put试试obj.addProperty

标签: android retrofit


【解决方案1】:

更新您的请求方法代码如下:

@Headers( "Content-Type: application/json; charset=utf-8")
    @POST("mpapi/seller/sellerprofilepost")
    Call<ResponseBody>
    updateProfile(@Header("Authorization") String token,
                  @Body RequestBody body);

在API调用方法中:

    private void updateProfile() {
            try {
                showLoader();
                JSONObject obj=new JSONObject();
                obj.put("firstname",first_name.getText().toString().trim());
                RequestBody bodyRequest = RequestBody.create(MediaType.parse("application/json"), obj.toString());
                call = api.updateProfile("Bearer k8yu1q0k790lw5y4ta49alfbtsxoxs1w",bodyRequest);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.isSuccessful()) {
                                JSONObject obj = new JSONObject(response.body().string());
                                dialog = Func.OneButtonDialog(mContext, obj.getString("message"), ProfileScreen.this);
                            } else {
                                JSONObject obj = new JSONObject(response.errorBody().string());
                                dialog = Func.OneButtonDialog(mContext, obj.getString("message"), ProfileScreen.this);
                            }
                        } catch (Exception e) {
                            dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), ProfileScreen.this);
                            e.printStackTrace();
                        }
                        hideLoader();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), ProfileScreen.this);
                        hideLoader();
                    }
                });
            } catch (Exception e) {
                dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), this);
                hideLoader();
                e.printStackTrace();
            }
        }

或者您可以refer this link 换用其他方式。

【讨论】:

  • 是的,我使用的是相同的代码,它对我来说工作正常。你有没有注意到我在 Request 方法和 API 调用中都使用了 RequestBody。
  • 你也可以参考这个答案。这是和你一样的问题。它使用 Model 类并在请求方法中传递该 Model 类。 stackoverflow.com/a/26065492/9293029
  • 是的,我正在尝试这个。
【解决方案2】:

感谢 Viraj Patel,我以以下方式实现了代码,并且运行良好 :)

我的请求方法代码如下:

@Headers( "Content-Type: application/json; charset=utf-8")
@PUT("users/me/password-shares/")
fun sharePassword(@Body jsonObject: RequestBody): Call<ResponseBody>

调用方法将是

val request = jsonObject.toString().toRequestBody("application/json".toMediaTypeOrNull());

var response = passwordService.sharePassword(request).execute()

【讨论】:

    【解决方案3】:

    如下更新您的retrofit 请求,

    retrofitResponse = new RetrofitResponse();
    CommonPojo obj;
    
    private void updateProfile() {
            try {
                showLoader();
                retrofitResponse.setFirst_name(first_name.getText().toString().trim());
                obj = new CommonPojo();
                obj.setJSONobj(retrofitResponse);
    
                call = api.updateProfile("Bearer k8yu1q0k790lw5y4ta49alfbtsxoxs1w",obj);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.isSuccessful()) {
                                JSONObject obj = new JSONObject(response.body().string());
                                dialog = Func.OneButtonDialog(mContext, obj.getString("message"), ProfileScreen.this);
                            } else {
                                JSONObject obj = new JSONObject(response.errorBody().string());
                                dialog = Func.OneButtonDialog(mContext, obj.getString("message"), ProfileScreen.this);
                            }
                        } catch (Exception e) {
                            dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), ProfileScreen.this);
                            e.printStackTrace();
                        }
                        hideLoader();
                    }
    
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), ProfileScreen.this);
                        hideLoader();
                    }
                });
            } catch (Exception e) {
                dialog = Func.OneButtonDialog(mContext, getResources().getString(R.string.ERROR_MSG), this);
                hideLoader();
                e.printStackTrace();
            }
        }
    

    RetrofitResponse.java

    public class RetrofitResponse {
    
    String first_name;
    
    public String getFirst_name() {
            return first_name;
        }
    
        public void setFirst_name(String first_name) {
            this.first_name = first_name;
        }
    
    }
    

    发送Json格式的post数据,CommonPojo.java

    public class CommonPojo {
    
     private RetrofitResponse JSONobj;
    
     public RetrofitResponse getJSONobj() {
            return JSONobj;
        }
    
        public void setJSONobj(RetrofitResponse JSONobj) {
            this.JSONobj = JSONobj;
        }
    
    }
    

    试试这个,如果需要任何帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-19
      • 2016-08-13
      • 1970-01-01
      • 2019-12-08
      • 2011-03-10
      • 2023-04-10
      • 2015-02-27
      • 1970-01-01
      相关资源
      最近更新 更多