因此,我正在使用请求构建器连接到我的API,这样我就可以接收一些数据供我的用户登录。有时因为我的API进入睡眠状态,这将需要超过默认的10秒才能请求,这使我的应用程序报告套接字超时错误。
我看过多个示例,但答案似乎已过时,或者似乎无法解决问题。
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, requestBody);
Request request = new Request.Builder()
.url(DataService.authUrl+DataService.policyName)
.post(body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Ocp-Apim-Subscription-Key", DataService.authSubscriptionKey)
.addHeader("Cache-Control", "no-cache")
.addHeader("appId", "CB563848-4B41-4D30-9ABE-9DF30508EABB")
.addHeader("hardwareId", Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID))
.addHeader("versionNumber", Globals.versionName)
.build();
okHttpClient.newCall(request).enqueue(new Callback() { blah blah blah
我试图将.setConnectTimeout
添加到我的构建器中,但这不起作用。
我尝试创建一个全新的OkHttpClient.Builder
,但这意味着我无法使用并发请求。
,如果我尝试使用
okHttpClient.connectTimeOut(10, TimeUnit.SECONDS)
,它不起作用。
我用Google搜索了很多东西,但是无法正常工作。任何建议都可以增加我的超时时间。
谢谢。
答案 0 :(得分:0)
尝试一下
public static WebService INSTANCE;
APIService mApiService;
public WebService() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.MINUTES).readTimeout(5, TimeUnit.MINUTES);
httpClient.interceptors().add(logging);
httpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Customize the request
Request request = original.newBuilder()
.header("Accept", "application/json")
.method(original.method(), original.body())
.build();
Response response = chain.proceed(request);
// Customize or return the response
return response;
}
}
);
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.getInstance().URLLOCAL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
mApiService = retrofit.create(APIService.class);
}
答案 1 :(得分:0)
尝试此代码:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();