Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON in POST request with retrofit [duplicate]

I've seen this questions many times and tried many solutions but without resolving my problem, I'm trying to send a json in a POST request using retrofit, I'm not an expert in programming so I may miss something obvious.

My JSON is in a string and looks like that:

{"id":1,"nom":"Hydrogène","slug":"hydrogene"}

My Interface (called APIService.java) looks like that:

@POST("{TableName}/{ID}/update/0.0")
Call<String> cl_updateData(@Path("TableName") String TableName, @Path("ID") String ID);

And my ClientServiceGenerator.java looks like that:

public class ClientServiceGenerator{
private static OkHttpClient httpClient = new OkHttpClient();

public static <S> S createService(Class<S> serviceClass, String URL) {
    Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.client(httpClient).build();
    return retrofit.create(serviceClass);
}}

And finally here is the code in my activity

APIService client = ClientServiceGenerator.createService(APIService.class, "http://mysiteexample.com/api.php/");
    Call<String> call = client.cl_updateData("atomes", "1");
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response, Retrofit retrofit) {
            if (response.code() == 200 && response.body() != null){
                Log.e("sd", "OK");
            }else{
                Log.e("Err", response.message()+" : "+response.raw().toString());
            }
        }

        @Override
        public void onFailure(Throwable t) {
            AlertDialog alertError = QuickToolsBox.simpleAlert(EditDataActivity.this, "updateFail", t.getMessage(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            alertError.show();
        }
    });

Tell me if you need anything else, hope someone could help me.

EDIT Didn't mention it first time but my JSON won't always be with the same keys (id, nom, slug).

like image 623
Teasel Avatar asked May 10 '16 12:05

Teasel


1 Answers

First you need to create an object to represent the json you need:

public class Data {
    int id;
    String nom;
    String slug;

    public Data(int id, String nom, String slug) {
        this.id = id;
        this.nom = nom;
        this.slug = slug;
    }
}

Then, modify your service to be able to send this object:

@POST("{TableName}/{ID}/update/0.0")
Call<String> cl_updateData(@Path("TableName") String TableName, @Path("ID") String ID, @Body Data data);

Finally, pass this object:

Call<String> call = client.cl_updateData("atomes", "1", new Data(1, "Hydrogène", "hydrogene"));

UPD

To be able to send any data use Object instead of Data:

@POST("{TableName}/{ID}/update/0.0")
Call<String> cl_updateData(@Path("TableName") String TableName, @Path("ID") String ID, 
        @Body Object data);
like image 152
Oleg Khalidov Avatar answered Sep 20 '22 15:09

Oleg Khalidov