Kasun Wanniarachchi
Kasun Wanniarachchi

Reputation: 544

http post setEntity using retrofit

I recently move to Retrofit, I want to replace this httpost set entity using Retrofit. How can i do it.

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("childId", childId);

    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObject.toString());
    httpPost.setEntity(entity);

this is what i was trying to do, but it dosent work,

    Observable<Item> getListOfFeed(@Body StringEntity params);

Upvotes: 1

Views: 1103

Answers (2)

Kasun Wanniarachchi
Kasun Wanniarachchi

Reputation: 544

finally figure out the answer, add a custom TypedJsonString class,

public class TypedJsonString extends TypedString {
    public TypedJsonString(String body) {
        super(body);
    }

    @Override public String mimeType() {
        return "application/json";
    }
}

convert my json object to TypedJsonString,

TypedJsonString typedJsonString = new TypedJsonString(jsonObject.toString());

changed the api class as follows,

Observable<Item> getListOfFeed(@Body TypedJsonString typedJsonString);

Upvotes: 1

Ravi
Ravi

Reputation: 35549

You can send request with Post using following code in Retrofit inside your API interface

public interface MyAPI{
 @FormUrlEncoded
 @POST("rest url")
 Call<Item> loadQuestions(@Field("parameter_name")String order);
}

Dont forget to mention @FormUrlEncoded, To call this function use this

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("url")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
MyAPI api=retrofit.create(MyAPI.class);
Call<Item> call=api.loadQuestions("pass your data here");
call.enqueue(new Callback<Item>() {
        @Override
        public void onResponse(Response<Item> response, Retrofit retrofit) {
            Log.e("response",response.message());

        }

        @Override
        public void onFailure(Throwable t) {

        }
});

Upvotes: 0

Related Questions