I want to Post data on API using body raw but always got null on response.body and data not send.
Here is my retrofit class:
public class ApiClient {
public static Retrofit retrofit;
private static final String BASE_URL = BuildConfig.BASE_URL;
public static Retrofit getRetrofitInstance(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
then here is the interface:
public interface SendData {
@POST("/")
Call<DataItem> sendData(@Body DataItem body);}
there is class model:
public class DataItem{
private String date;
private String imgUrl;
private double probability;
private String latitude;
private String longtitude;
private String className;
public DataItem(String date, String imgUrl, double probability, String latitude, String longtitude, String className) {
this.date = date;
this.imgUrl = imgUrl;
this.probability = probability;
this.latitude = latitude;
this.longtitude = longtitude;
this.className = className;
}
public String getDate(){
return date;
}
public String getImgUrl(){
return imgUrl;
}
public double getProbability(){
return probability;
}
public String getLatitude(){
return latitude;
}
public String getLongtitude(){
return longtitude;
}
public String getClassName(){
return className;
}
}
here is call the retrofit to post data:
DataItem data = new DataItem(currentDate, imgUrl, probability, latitude, longitude, class_name);
SendData service = ApiClient.getRetrofitInstance().create(SendData.class);
Call<DataItem> call = service.sendData(data);
call.enqueue(new Callback<DataItem>() {
@Override
public void onResponse(Call<DataItem> call, Response<DataItem> response) {
String result = String.valueOf(response.body());
Log.d("MainActivity", "response = " + response.message());
Log.d("MainActivity", "result = " + result);
timingSendData();
Toast.makeText(MainActivity.this, "Data Send!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<DataItem> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
Log.d(TAG, "onFailure: "+t.getLocalizedMessage());
Toast.makeText(MainActivity.this, "Cannot Send Data!", Toast.LENGTH_SHORT).show();
}
});
I already used serilaizaton in model also I used hashmap<string,string> but still not able to post data. API also tested in postman and it's worked
EDIT: after follow @DinkarKumar suggestion, Post data to API is work. but it makes me confused that the response is not on method onResponse() but on method onFailure(), at least data can be Post to API. PS: I moved the URL of API