Retry interceptor:

/** * @slf4j public class RetryInterceptor implements Interceptor {@override public Response intercept(Chain chain) throws IOException { return retry(chain); } public Response retry(Chain chain) throws IOException { Request request = chain.request(); ParentRetryRequestParam retryTag = request.tag(ParentRetryRequestParam.class); Response response = null; try { response = chain.proceed(request); if (! response.isSuccessful() && Objects.nonNull(retryTag) && retryTag.getCurrentCount() < retryTag.getRetryCount()) { retryTag.setCurrentCount(retryTag.getCurrentCount() + 1); response = retry(chain); } } catch (Exception e) { assert retryTag ! = null; log.info("RetryInterceptor: request {} is not successful-> request count {} because {}", request.url(), retryTag.getCurrentCount(), e.getMessage()); if (retryTag.getCurrentCount() < retryTag.getRetryCount()) { retryTag.setCurrentCount(retryTag.getCurrentCount() + 1); response = retry(chain); }} // The synchronous request directly throws an exception, which is handled by the outer call function, and the asynchronous request enters the callback interface. If (objects.isnull (response)) {throw new IOException(" request "+ retryTag.getCurrentCount() +" request failed "); } return response; }}Copy the code

Requesting client

@Configuration public class RequestClientConfig { /** * * * @return */ @Bean public okhttp3.OkHttpClient OkHttpClient() { okhttp3.OkHttpClient okHttpClient = new okhttp3.OkHttpClient.Builder() EventListenerFactory (HttpEventListener. FACTORY) / / read the default timeout readTimeout (10000, Timeunit.milliseconds) // default connect. connectTimeout(10000, timeunit.milliseconds) // default writeTimeout. WriteTimeout (10000, writeTimeout) TimeUnit. MILLISECONDS) / / close the default retry interceptor retryOnConnectionFailure (false) / / add custom retry interceptors. AddInterceptor (new RetryInterceptor ())  .build(); return okHttpClient; }}Copy the code

Encapsulate request parameters:

package com.baturu.pq.business.okhttp.param; import com.baturu.pq.business.im.yunxin.param.ParentRetryRequestParam; import com.baturu.pq.business.okhttp.config.TimeoutConfig; import lombok.Builder; import lombok.Data; import java.util.Map; /** * HTTP request parameter ** @author shenweiquan */ @data @Builder public class HttpRequestParam {/** * request address */ private String url; /** * timeout */ private TimeoutConfig TimeoutConfig; /** * private Map<String, String> headerMap; /** * Private Map<String, Object> paramMap; */ private ParentRetryRequestParam retryRequestParam; /** * Whether the form has been submitted */ private Boolean isForm; /** * request body json submission */ private Object body; }Copy the code

Packaged utility classes:

package com.baturu.pq.business.okhttp.util; import com.alibaba.fastjson.JSON; import com.baturu.pq.business.im.yunxin.param.ParentRetryRequestParam; import com.baturu.pq.business.okhttp.callback.OkHttpCallback; import com.baturu.pq.business.okhttp.config.TimeoutConfig; import com.baturu.pq.business.okhttp.param.HttpRequestParam; import lombok.Builder; import lombok.extern.slf4j.Slf4j; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.apache.commons.lang3.BooleanUtils; import org.apache.http.NameValuePair; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; /** * @author shenweiquan */ @slf4j @builder public class OkHttpUtils {private OkHttpClient client; /** * @param client */ public OkHttpUtils(OkHttpClient client) { this.client = client; } /** * Public Response httpPostSync(HttpRequestParam param) {Request.Builder Request = this.httpPost(param); try (Response response = client.newCall(request.build()).execute()) { return response; } catch (IOException e) {log.error(" send request exception, url:{}; {}", param.getUrl(), e); return null; Public void httpPostAsync(HttpRequestParam param, OkHttpCallback okHttpCallback) { Request.Builder request = this.httpPost(param); this.async(request, okHttpCallback); } public Response httpGetSync(HttpRequestParam param) {request.builder Request = this.httpget (param); try (Response response = client.newCall(request.build()).execute()) { return response; } catch (IOException e) {log.error(" send request exception, url:{}; {}", param.getUrl(), e); return null; } } public void httpGetAsync(HttpRequestParam param, OkHttpCallback callback) { Request.Builder request = this.httpGet(param); this.async(request, callback); } private request. Builder httpPost(HttpRequestParam param) {private request. Builder httpPost(HttpRequestParam param) { Request.Builder request = new Request.Builder(); request.url(param.getUrl()); if (Objects.nonNull(param.getHeaderMap())) { this.setHeader(request, param.getHeaderMap()); } if (objects.nonnull (param.getTimeoutConfig())) {request.tag(timeoutconfig.class, param.getTimeoutConfig()); } / / custom retries the if (Objects. NonNull (param. GetRetryRequestParam ())) {request. The tag (ParentRetryRequestParam. Class, param.getRetryRequestParam()); } if (Objects.nonNull(param.getIsForm()) && BooleanUtils.isTrue(param.getIsForm())) { List<NameValuePair> bodyForm = JSON.parseArray(JSON.toJSONString(param.getBody()), NameValuePair.class); this.bodyForm(request, bodyForm); } else { this.body(request, param.getBody()); } return request; Public request. Builder httpGet(HttpRequestParam param) {request. Builder Request = new Request.Builder().get(); HttpUrl.Builder urlBuilder = HttpUrl.parse(param.getUrl()).newBuilder(); If (objects.nonnull (param.getParamMap())) {// Get request parameters for (map.entry <String, Object> Entry: param.getParamMap().entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); } } request.url(urlBuilder.build()); this.setHeader(request, param.getHeaderMap()); If (objects.nonnull (param.getTimeoutConfig())) {request.tag(timeoutconfig. class, param.getTimeoutConfig())); } / / custom retries the if (Objects. NonNull (param. GetRetryRequestParam ())) {request. The tag (ParentRetryRequestParam. Class, param.getRetryRequestParam()); } return request; } /** * private void bodyForm(Request.Builder Request, List<NameValuePair> bodyForm) { FormBody.Builder formBody = new FormBody.Builder(); bodyForm.stream() .map(v -> { return formBody.add(v.getName(), v.getValue()); }); RequestBody requestBody = formBody.build(); request.post(requestBody); Private void body(Request.Builder Request, Object Body) {String jsonStr = ""; if (Objects.nonNull(body)) { jsonStr = JSON.toJSONString(body); } RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr); request.post(requestBody); } @param request */ private void setHeader(request.Builder Request, Map<String, String> headerMap) { if (Objects.nonNull(headerMap)) { try { for (Map.Entry<String, String> entry : headerMap.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } catch (Exception e) { e.printStackTrace(); Public void async(Request.Builder Request); /** @param okHttpCallback */ OkHttpCallback okHttpCallback) { client.newCall(request.build()).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { okHttpCallback.failed(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { okHttpCallback.success(call, response); }}); }}Copy the code

Testing:

*/ @test public void test4() {HttpRequestParam = httprequestParam.builder () .url("https://github.com") .timeoutConfig(TimeoutConfig.builder().socketTimeout(1).build()) .retryRequestParam(new ParentRetryRequestParam(10, 1)) .build(); Dispatcher dispatcher = client.dispatcher(); / * * * maximum number of requests * / dispatcher setMaxRequests (64); / * * * the same domain name. At the same time there is the maximum number of requests * / dispatcher setMaxRequestsPerHost (8); OkHttpUtils okHttpUtils = OkHttpUtils.builder() .client(client.newBuilder() .addInterceptor(new TimeoutInterceptor()) .addInterceptor(new RetryInterceptor()) .build()) .build(); okHttpUtils.httpGetSync(requestParam); }Copy the code