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
Try this
1.APIInterface.java
public interface APIInterface {
/*Login*/
@POST("users/login")
Call savePost(@HeaderMap Map header, @Body UserModel loginRequest);
}
2.ApiClient.java
public class ApiClient {
public static final String BASE_URL = "baseurl";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
.connectTimeout(30, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.MINUTES)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
API call
public void sendPost(JSONObject jsonObject) {
LoginRequestModel loginRequest = new LoginRequestModel(userName, userPassword);
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
APIInterface appInterface = ApiClient.getClient().create(APIInterface.class);
System.out.println("Final" + new Gson().toJson(loginRequest));
Call call = appInterface.savePost(header, loginRequest);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
hideProgressDialog();
if (response.body()!=null) {
} else {
Toast.makeText(mContext, "Invalid credentials", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
}
Dependencies in Gradle file
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
5.User Model
public class UserModel {
@SerializedName("usename")
@Expose
String userEmail;
@SerializedName("password")
@Expose
String userPassword;
public UserModel(String userEmail, String userPassword) {
this.userEmail = userEmail;
this.userPassword = userPassword;
}
}