android - 所有 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);
}
解决方案
推荐阅读
- javascript - 触发 Firestore 离线执行
- python - 图像分割中的欧几里得距离
- vba - 将组合框添加到 userForm 时出现内存不足错误
- symfony - 如果在树枝中为空,则设置默认值
- python - 在 django rest 框架中的嵌套序列化程序中上传图像
- mybatis - 添加@Transactional函数解决游标继续打开后卡在批量插入
- pre-commit - 为我的存储库设置 Talisman 时提交更改时出现意外错误
- php - 如何按降序动态排序年份范围数组
- android-studio - 更新到新的 android studio artic fox (2020.3.1) 后出现主题问题
- symfony - 使用 botman 发送电子邮件