3
votes

Comment supprimer «nameValuePairs» dans une demande JSON à l'aide de Retrofit?

J'essaie d'envoyer des données brutes dans une requête POST mais la clé nameValuePairs est concaténée avec mon JSON.

Voici ma méthode de requête: -

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

J'envoie ceci: -

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

mais au backend, ils reçoivent: -

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

    }
}

Méthode pour appeler api: - p >

{
    "firstname": "test1ff"
}

Méthode d'appel de mise à niveau: - voici ma méthode d'appel de mise à niveau où je définis l'URL de base, les en-têtes, etc.

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


9 commentaires

plz ajouter du code


ajoutez du code à partir duquel vous appelez la méthode updateProfile ().


Au lieu d'utiliser JSONObject d'Android, utilisez JsonObject de GSON et construisez l'objet avec la méthode addProperty (String property, Value)


au lieu de obj.put essayez obj.addProperty


vérifiez ceci: stackoverflow.com/a/36312617/8475893


J'utilise JSONObject et non JsonObject


J'ai essayé le code, il m'est également arrivé de ne pas savoir pourquoi vous pouvez utiliser un hashmap dans le corps ou ajouter votre propre classe personnalisée


J'ai déjà essayé.


@Kartika vous avez essayé le hashmap?


3 Réponses :


2
votes

Mettez à jour le code de votre méthode de requête comme suit:

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

Dans la méthode d'appel d'API:

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

Ou vous pouvez référez-vous à ce lien pour d'autres moyens.


3 commentaires

Oui, j'utilise le même code et cela fonctionne très bien pour moi. Avez-vous remarqué que j'utilise RequestBody dans la méthode Request ainsi que dans l'appel API.


Vous pouvez également vous référer à cette réponse. C'est le même problème que le vôtre. Il utilise la classe Model et transmet cette classe Model dans la méthode de demande. stackoverflow.com/a/26065492/9293029


Ya j'essaye ça.



0
votes

Mettez à jour votre demande de retrofit comme ci-dessous,

public class CommonPojo {

 private RetrofitResponse JSONobj;

 public RetrofitResponse getJSONobj() {
        return JSONobj;
    }

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

}

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

}

Envoyez les données de publication avec Format Json , CommonPojo.java

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

Essayez ceci et faites-moi savoir si vous avez besoin d'aide.


0 commentaires

0
votes

Grâce à Viraj Patel, j'ai implémenté le code de la manière ci-dessous et cela fonctionne très bien :)

Mon code de méthode de requête comme suit:

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

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

La méthode d'appel sera être

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


0 commentaires