RetryInterceptor.java 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2019-2029, Dreamlu (596392912@qq.com & www.dreamlu.net).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17 18
package net.dreamlu.mica.http;

19
import lombok.RequiredArgsConstructor;
20
import net.dreamlu.mica.core.retry.IRetry;
21 22 23
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
24
import okhttp3.ResponseBody;
25

26
import javax.annotation.Nullable;
27
import java.io.IOException;
28
import java.util.function.Predicate;
29 30 31 32

/**
 * 重试拦截器,应对代理问题
 *
33
 * @author L.cm
34
 */
35
@RequiredArgsConstructor
36
public class RetryInterceptor implements Interceptor {
37 38 39
	private final IRetry retry;
	@Nullable
	private final Predicate<ResponseSpec> respPredicate;
40 41 42 43

	@Override
	public Response intercept(Chain chain) throws IOException {
		Request request = chain.request();
44
		return retry.execute(() -> {
45 46 47 48 49 50 51
			Response response = chain.proceed(request);
			// 结果集校验
			if (respPredicate == null) {
				return response;
			}
			// copy 一份 body
			ResponseBody body = response.peekBody(Long.MAX_VALUE);
52
			try (HttpResponse httpResponse = new HttpResponse(response)) {
53 54 55
				if (respPredicate.test(httpResponse)) {
					throw new IOException("Http Retry ResponsePredicate test Failure.");
				}
56 57 58
			}
			return response.newBuilder().body(body).build();
		});
59 60 61
	}

}