首页 > 解决方案 > 所有 Retrofit 2 POST 请求都超时并且服务器接收到空字符串

问题描述

我按照codepath上的指南通过改造来实现 POST 请求。一切似乎都很好,除了所有请求都抛出timeout错误,而且它们似乎有空的身体。我不明白如果开始时有超时,服务器将如何注册请求,除了空主体请求对我的目的没有太大帮助之外。

我尝试使用超时为 60 秒的 okhttp 配置我的改造客户端,我认为这已经足够了,但这并不能解决超时问题。传递给改造 api 服务的对象是非空的且已填充。代码路径指南提到改造会使用配置的 gson 自动将对象转换为 JSON。所以我认为转换不会导致任何问题,我尝试发送实际的 JSON 字符串来确认。

请参阅下面的相关代码以供参考。对于 1) 每次请求超时和 2) 发送带有空字符串的正文,我将不胜感激:)

public class RetrofitClient {
    // Trailing slash is needed
    public static final String BASE_URL = "https://www.hidden-for-privacy.com/";

    public static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .build();

    public static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd")
            .create();

    public static Retrofit instance = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okHttpClient)
            .build();

    public static ApiEndpointInterface service =
            instance.create(ApiEndpointInterface.class);
}
------------------------------------------------------------------------------
public class ApiService {
    ApiEndpointInterface request;

    public ApiService() {
        request = RetrofitClient.service;
    }

    public void createDamage(Damage damage) {
        Log.d("ApiService.createDamage", RetrofitClient.gson.toJson(damage));

        Call<Damage> call = request.createDamage(damage);
        call.enqueue(new Callback<Damage>() {
            @Override
            public void onResponse(Call<Damage> call, Response<Damage> response) {
                Log.d("ApiService post-damage success", response.message());
            }
            @Override
            public void onFailure(Call<Damage> call, Throwable t) {
                Log.d("ApiService post-damage fail", t.getMessage());
            }
        });
    }
}
------------------------------------------------------------------------------
public interface ApiEndpointInterface {
    // Request method and URL specified in the annotation
    @POST("api/damages/damage")
    Call<Damage> createDamage(@Body Damage damage);
}

标签: androidexpressretrofitokhttp

解决方案


推荐阅读