I would like to call a POST Method(Magento REST API) in Retrofit with a JSON data(provide JSON as JsonObject). For that, I call as follow from the postman and work fine for me.
I have done the android parts as follow,
API INTERFACE
public interface APIService {
@POST("seq/restapi/checkpassword")
@Headers({
"Content-Type: application/json;charset=utf-8",
"Accept: application/json;charset=utf-8",
"Cache-Control: max-age=640000"
})
Call<Post> savePost(
@Body JSONObject jsonObject
);}
APIUtility class as
public class ApiUtils {
private ApiUtils() {
}
public static final String BASE_URL = "http://xx.xxxx.xxx.xxx/api/rest/";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
RetrofitClient class as
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
And finally, call the function as follows
public void sendPost(JSONObject jsonObject) {
Log.e("TEST", "****************************************** jsonObject" + jsonObject);
mAPIService.savePost(jsonObject).enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()) {
}
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}
CallRetrofit API with the POST method with a body.
3
Answers
Change your code to something like this, GsonConverterFactory converts a User object to json itself.
This is User Class:
I think the
GsonConverterFactory
you’ve set up for all calls converts your JSONObject to json. That’s why your call’s body may look quite different than you think. This is the result ofgson.toJson(new JSONObject())
:Try changing the object you send to this:
and then update your call
To ensure your call is correct, call
Try this
1.APIInterface.java
2.ApiClient.java
API call
}
Dependencies in Gradle file
5.User Model