fix(http): timeout on http request

This commit is contained in:
hyb1996 2018-04-11 16:25:15 +08:00
parent dc790a297c
commit b49ea34585
2 changed files with 80 additions and 4 deletions

View File

@ -1,6 +1,10 @@
module.exports = function(runtime, scope){
importPackage(Packages["okhttp3"]);
importClass(com.stardust.autojs.core.http.MutableOkHttp);
var http = {};
http.__okhttp__ = new MutableOkHttp();
http.get = function(url, options, callback){
options = options || {};
options.method = "GET";
@ -8,10 +12,7 @@ module.exports = function(runtime, scope){
}
http.client = function(){
if(!http._client_){
http._client_ = new OkHttpClient();
}
return http._client_;
return http.__okhttp__.client();
}
http.post = function(url, data, options, callback){

View File

@ -0,0 +1,75 @@
package com.stardust.autojs.core.http;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Stardust on 2018/4/11.
*/
public class MutableOkHttp extends OkHttpClient {
private OkHttpClient mOkHttpClient;
private int mMaxRetries = 3;
private long mTimeout = 30 * 1000;
private Interceptor mRetryInterceptor = chain -> {
Request request = chain.request();
Response response = chain.proceed(request);
int tryCount = 0;
while (!response.isSuccessful() && tryCount < getMaxRetries()) {
tryCount++;
response = chain.proceed(request);
}
return response;
};
public MutableOkHttp() {
mOkHttpClient = newClient(new OkHttpClient.Builder());
}
public OkHttpClient client() {
return mOkHttpClient;
}
protected OkHttpClient newClient(Builder builder) {
builder.readTimeout(getTimeout(), TimeUnit.MILLISECONDS)
.writeTimeout(getTimeout(), TimeUnit.MILLISECONDS)
.connectTimeout(getTimeout(), TimeUnit.MILLISECONDS);
for (Interceptor interceptor : getInterceptors()) {
builder.addInterceptor(interceptor);
}
return builder.build();
}
public Iterable<? extends Interceptor> getInterceptors() {
return Collections.singletonList(mRetryInterceptor);
}
public int getMaxRetries() {
return mMaxRetries;
}
public void setMaxRetries(int maxRetries) {
mMaxRetries = maxRetries;
}
public long getTimeout() {
return mTimeout;
}
public void setTimeout(long timeout) {
mTimeout = timeout;
muteClient();
}
protected synchronized void muteClient() {
mOkHttpClient = newClient(mOkHttpClient.newBuilder());
}
}