依赖jar包
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
代码
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.httpclient.HttpException;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class HttpResponseConnectTimeout {
public static void main(String[] args) throws HttpException, IOException {
String url = "";
System.out.println(httpRequest(url,1,2));
}
public static String httpRequest(String url, int maxRentry,int timeout ) {
String responseResult;
Response response = null;
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(timeout, TimeUnit.SECONDS)
.readTimeout(timeout, TimeUnit.SECONDS)
.writeTimeout(timeout, TimeUnit.SECONDS)
.addInterceptor(new HttpResponseConnectTimeout.OkhttpInterceptor(maxRentry))
.retryOnConnectionFailure(false)
.build();
Request request = new Request.Builder()
.url(url)
.method("GET", null)
.build();
try {
response = client.newCall(request).execute();
if (response != null) {
responseResult = response.body().string();
return responseResult;
} else {
System.out.println("接口请求超时");
return null;
}
} catch (Exception e) {
System.out.println("重试2次后,访问超时.");
return null;
}
}
public static class OkhttpInterceptor implements Interceptor {
private int maxRentry;
public OkhttpInterceptor(int maxRentry) {
this.maxRentry = maxRentry;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
return retry(chain, 0);
}
Response retry(Chain chain, int retryCent) {
Request request = chain.request();
Response response = null;
try {
response = chain.proceed(request);
} catch (Exception e) {
if (maxRentry > retryCent) {
return retry(chain, retryCent + 1);
}
} finally {
return response;
}
}
}
}
|