3

I am trying to send raw data in POST request but nameValuePairs key get concated with my JSON.

Here is my request method:-

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

I am sending this:-

{
    "firstname": "test1ff"
}

but at backend they are receiving :-

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

    }
}

Method for calling 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();
        }
    }

Retrofit call method :- here is my retrofit call method where I am setting base url, headers etc

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;
    }
Kartika Vij
  • 203
  • 3
  • 17

4 Answers4

3

Update your request method code as follow:

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

In API Calling Method:

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

Or you can refer this link for alternate ways.

Viraj Patel
  • 2,113
  • 16
  • 23
  • Yes, I am using the same code and it is working fine for me. Have you notice that I am using RequestBody in Request method as well as in API call. – Viraj Patel Feb 22 '19 at 09:39
  • You can also refer to this answer. It is the same problem as yours. It uses the Model class and passes that Model class in the request method. https://stackoverflow.com/a/26065492/9293029 – Viraj Patel Feb 22 '19 at 09:42
  • Ya I am trying this. – Kartika Vij Feb 22 '19 at 09:46
1

Thanks to Viraj Patel, I have implemented code in below way and it is working fine :)

My request method code as follow:

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

Calling method will be

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

var response = passwordService.sharePassword(request).execute()
Siddhpura Amit
  • 14,534
  • 16
  • 91
  • 150
0

Update your retrofit request as below,

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

}

Send post data with Json format, CommonPojo.java

public class CommonPojo {

 private RetrofitResponse JSONobj;

 public RetrofitResponse getJSONobj() {
        return JSONobj;
    }

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

}

Try this and let me know if any help needs.

Android
  • 1,420
  • 4
  • 13
  • 23
0

Use Map instead of JSONObject as follow:

@Headers( "Content-Type: application/json; charset=utf-8")
@POST("mpapi/seller/sellerprofilepost")
Call<ResponseBody>
updateProfile(@Header("Authorization") String token,
              @Body Map<Object,Object> body);
tho nguyen
  • 126
  • 2
  • 4