【问题标题】:Retrofit2 - Requests are always status 404 and the response nullRetrofit2 - 请求总是状态 404 并且响应为空
【发布时间】:2017-07-07 04:16:47
【问题描述】:

我看到其他 3 篇关于此的 SO 帖子,但解决方案不起作用。每个端点都以status code 404 返回,并且在retrofit2 中响应为空。这是我的改造实现:

改造服务:

//code setup for HTTP client for Retrofit goes here
......
......
public static void initRetrofit() {
        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}

构建配置

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
        debug {
            versionNameSuffix ".staging"
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
}

端点:

public interface APIServices {

    @POST("api/users/register.json")
    Call<HttpResponse<Auth>> register(@Body RegisterData data);

}

我在这里做错了什么?其他 SO 线程建议从 /api/users/register.json 中删除 /api/,我这样做了,但响应没有变化。

【问题讨论】:

    标签: android retrofit2


    【解决方案1】:

    您没有为 Retrofit 对象设置 HTTP 客户端。尝试为此使用OkHttpClient

    public static void initRetrofit() {
        OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(Config.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .readTimeout(Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
    
            builder =
                    new Retrofit.Builder()
                            .baseUrl(BuildConfig.BASE_URL)
                            .client(client)
              .addConverterFactory(GsonConverterFactory.create(initGson()));
    }
    

    另外,检查您的 API 地址 - 尝试为此使用一些服务(例如 Postman):输入您的地址(从您的代码中为:'http://MY_SERVICE.azurewebsites.netapi/users/register.json')。

    【讨论】:

    • 这些已经设置好了,我没有在答案中包含。这是假设的,抱歉我没有提到:D
    【解决方案2】:

    Retrofit2 基本网址应以斜杠结尾。尝试添加它:

    buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net/\""
    

    【讨论】:

    • 那么在基本 url 中添加一个/ 并从/api/users 端点中删除/
    • 是的,这就是惯例
    猜你喜欢
    • 2019-05-03
    • 1970-01-01
    • 2017-08-10
    • 2018-08-08
    • 2017-10-31
    • 1970-01-01
    • 2022-11-13
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多