java - 无法停止改装发送
问题描述
我使用改造和 OkHttp3 库将一些消息发送到服务器并将其设置如下:
okClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
当我想发送一条大消息(例如,大约需要 2 分钟)时,Retrofit 会完全发送我的文件,2 分钟后,我收到了TimeOut
消息。如果我希望在 15 秒后停止发送并向我显示错误消息。
是否有我必须遵守的特定项目?请指导我。
或者建议我在 15 秒后中断此操作的标准方法。
我的代码:
class RetrofitFactory {
private static final RetrofitFactory INSTANCE = new RetrofitFactory();
public static RetrofitFactory getInstance() {
return INSTANCE;
}
public OkHttpClient getOkHttp()
{
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15,TimeUnit.SECONDS)
.addInterceptor(new GzipRequestInterceptor())
.addInterceptor(interceptor)
.build();
return okClient;
}
public myInterface getlimit()
{
if (retrofit == null) {
OkHttpClient okClient = getOkHttp();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
retrofit = new Retrofit.Builder()
.client(okClient)
.baseUrl(BuildConfig.BASEURL)
.addConverterFactory(JacksonConverterFactory.create(objectMapper))
.build();
}
return retrofit.create(myInterface.class);
}
}
public interface myInterface{
@POST("api/ReadingApi/Something")
Call<Something> DoReading(
@Body List<Something> list,
@Header("Authorization") String auth);
}
Call<DoReadResult> x = RetrofitFactory.getInstance().getlimit().DoReading(
data, "Something");
response = x.execute();
更新:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
解决方案
正如您所说,您正在使用 retrofit ,因此您需要使用 retrofit Call 轻松取消您的通话:
Call<ResponseBody> call =
uploadService.uploadSomething(fileUrl);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "request success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "request failed");
}
});
}
call.cancel();
用 call.cancel(); 您可以取消您的请求。
在这里查看更多:
推荐阅读
- ios - 在 UITextView 中快速键入时光标位置跳跃
- javascript - 如何在一页上显示两个动态样条图?
- githooks - 用于防止未知用户提交的 Bitbucket 自定义预接收挂钩
- dart - flutter bottomsheet with notch(类似于bottomNavigationBar:BottomAppBar的shape属性)
- python-3.x - 如何使用 uWSGI 和 Nginx 运行烧瓶 appbuilder
- json - 使用 Node.js 发布 HTTPS JSON 数据(标题+正文)的简单方法
- javascript - 节点类型错误:承诺解析器#
不是函数 - highcharts - Highcharts:如何在条形图系列顶部设置独特的图像
- java - 我可以在没有 finally 块的情况下编写相同的代码吗?
- java - 用百里香添加 css