下面是一个简单的Java代码示例,演示了如何设置超时时间和实现重试机制:
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class ApiCaller {
private static final int MAX_RETRIES = 3;
private static final int SOCKET_TIMEOUT = 10; // seconds
private OkHttpClient client;
public ApiCaller() {
client = new OkHttpClient.Builder()
.connectTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS)
.build();
}
public String callApi(String url) throws IOException {
int retryCount = 0;
while (retryCount < MAX_RETRIES) {
try {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (SocketTimeoutException e) {
System.out.println("接口超时,进行重试:" + (retryCount + 1));
retryCount++;
}
}
throw new IOException("接口调用超时");
}
public static void main(String[] args) {
ApiCaller apiCaller = new ApiCaller();
try {
String response = apiCaller.callApi("https://example.com/api");
System.out.println("接口调用成功,响应:" + response);
} catch (IOException e) {
System.out.println("接口调用失败:" + e.getMessage());
}
}
}
在上述代码中,首先创建了一个带有超时设置的OkHttpClient对象。然后,在callApi
方法中,通过循环结构进行接口调用,并在接口超时时进行重试。当达到重试次数上限后,抛出异常表示接口调用超时。在main
方法中,示例了如何使用ApiCaller
对象进行接口调用,并处理接口超时的情况。