ApiClient.java 类 -
public class ApiClient {
public static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
接口(interface) -
public interface ApiInterface {
@POST("posts/1")
Call<ModelClass> savePost();
}
在 Activity 的onCreate中-
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ModelClass> call = apiService.savePost();
call.enqueue(new Callback<ModelClass>() {
@Override
public void onResponse(Call<ModelClass>call, Response<ModelClass> response) {
Log.i(TAG,"response is "+response.body());
Log.i(TAG,"response code is "+response.code());
}
@Override
public void onFailure(Call<ModelClass>call, Throwable t) {
// Log error here since request failed
Log.i(TAG, t.toString());
}
});
我在 Gradle 中包含的依赖项 -
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
为什么retrofit返回404响应码,请问上面的代码有问题吗? 提前致谢。
最佳答案
兄弟,你的代码没问题,问题出在 api 上。 当我在 POSTMAN 的 post 方法中点击你的 api 时,它显示 404 Not Found 所以请检查你的服务器
但是它没有将空的 json 对象显示为正文,所以可能缺少参数并且您使用 404 状态来显示它,这是一种不好的做法,仅当此 api 不存在时才显示 404,并为此使用其他错误代码,如 409,422行动类型,让你更清楚回应
关于android - Retrofit 返回 404 响应码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978479/