【发布时间】:2021-08-18 21:55:42
【问题描述】:
我想使用 body raw 在 API 上发布数据,但 response.body 上总是为 null 并且数据未发送。
这是我的改装课:
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;
}
}
然后是界面:
public interface SendData {
@POST("/")
Call<DataItem> sendData(@Body DataItem body);}
有类模型:
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;
}
}
这里调用改造来发布数据:
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();
}
});
我已经在模型中使用了 serilaizaton,我也使用了 hashmap
编辑:遵循@DinkarKumar 的建议后,将数据发布到 API 即可。但这让我感到困惑的是,响应不是在方法 onResponse() 上而是在方法 onFailure() 上,至少数据可以发布到 API。 PS:我移动了API的URL
【问题讨论】:
-
你得到什么错误代码?
-
@DinkarKumar 没有错误,没有消息但 API 中没有添加数据
-
它的 200 ok 状态?
-
@DinkarKumar 不,不是,我已经检查过了。状态码 = 500