Как удалить «nameValuePairs» в запросе JSON с помощью Retrofit? - PullRequest
0 голосов
/ 22 февраля 2019

Я пытаюсь отправить необработанные данные в запросе 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;
    }

Ответы [ 2 ]

0 голосов
/ 22 февраля 2019

Обновите ваш запрос 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, CommonPojo.java

public class CommonPojo {

 private RetrofitResponse JSONobj;

 public RetrofitResponse getJSONobj() {
        return JSONobj;
    }

    public void setJSONobj(RetrofitResponse JSONobj) {
        this.JSONobj = JSONobj;
    }

}

Попробуйте и дайте мне знать, если потребуется какая-либо помощь.

0 голосов
/ 22 февраля 2019

Обновите код метода запроса следующим образом:

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

Или вы можете см. Эту ссылку дляальтернативные пути.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...