android - Retrofit 返回 404 响应码

标签 android retrofit2

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/

相关文章:

使用retrofit2上传图片时出现Java.io.FileNotFoundException

Android:splitActionBarWhenNarrow 的问题

java - 从适配器访问 fragment

java - 将注释插入 Jackson 的 Retrofit 请求中

java - 改造 + RxJava : How to request for multiple request in order and assemble results in single Observable?

java - 使用 Retrofit 2 在多部分的 PartMap 请求中为同一参数使用多个值

android - GCM 使用两个不同的工作注册 ID 进行注册

android - 多个应用程序安装程序或多个可启动项

android - 从 Activity 调用 DialogFragment 导致 "IllegalStateException: fragment not attached to Activity"

java - 改造Gson自定义json通用转换器