use of okhttp3.EventListener in project micrometer by micrometer-metrics.
the class OkHttpMetricsEventListenerTest method timeFailureDueToTimeout.
@Test
void timeFailureDueToTimeout() {
Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build();
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MILLISECONDS).eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests").uriMapper(req -> req.url().encodedPath()).tags(Tags.of("foo", "bar")).build()).build();
try {
client.newCall(request).execute().close();
} catch (IOException ignored) {
// expected
}
assertThat(registry.get("okhttp.requests").tags("uri", "UNKNOWN", "status", "IO_ERROR").timer().count()).isEqualTo(1L);
}
use of okhttp3.EventListener in project nzbhydra2 by theotherp.
the class WebHooks method onNzbDownloadEvent.
@Async
@EventListener
public void onNzbDownloadEvent(FileDownloadEvent downloadEvent) throws IOException {
String downloadHook = System.getProperty("nzbhydra.hooks.download");
if (!Strings.isNullOrEmpty(downloadHook)) {
if (downloadEvent.getDownloadEntity().getAccessSource() == SearchSource.INTERNAL) {
try {
OkHttpClient client = requestFactory.getOkHttpClientBuilder(URI.create(downloadHook)).build();
String content = objectMapper.writeValueAsString(downloadEvent.getDownloadEntity());
Response response = client.newCall(new Builder().url(downloadHook).method("PUT", RequestBody.create(MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE), content)).build()).execute();
response.close();
logger.debug("Called download web hook with response {}", response);
} catch (IOException e) {
logger.error("Unable to execute webhook to {} on download event", downloadHook);
}
}
}
}
use of okhttp3.EventListener in project okhttp by square.
the class LoggingEventListenerTest method testCacheEvents.
@Test
public void testCacheEvents() {
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
Response response = new Response.Builder().request(request).code(200).message("").protocol(HTTP_2).build();
EventListener listener = loggingEventListenerFactory.create(call);
listener.cacheConditionalHit(call, response);
listener.cacheHit(call, response);
listener.cacheMiss(call);
listener.satisfactionFailure(call, response);
logRecorder.assertLogMatch("cacheConditionalHit: Response\\{protocol=h2, code=200, message=, url=" + url + "\\}").assertLogMatch("cacheHit: Response\\{protocol=h2, code=200, message=, url=" + url + "\\}").assertLogMatch("cacheMiss").assertLogMatch("satisfactionFailure: Response\\{protocol=h2, code=200, message=, url=" + url + "\\}").assertNoMoreLogs();
}
use of okhttp3.EventListener in project failsafe by jhalterman.
the class OkHttpTesting method test.
private <T> void test(FailsafeExecutor<Response> failsafe, Call when, Then<Response> then, int expectedStatus, T expectedResult, Class<? extends Throwable>[] expectedExceptions) {
AtomicReference<CompletableFuture<Response>> futureRef = new AtomicReference<>();
AtomicReference<ExecutionCompletedEvent<Response>> completedEventRef = new AtomicReference<>();
Waiter completionListenerWaiter = new Waiter();
EventListener<ExecutionCompletedEvent<Response>> setCompletedEventFn = e -> {
completedEventRef.set(e);
completionListenerWaiter.resume();
};
List<Class<? extends Throwable>> expected = new LinkedList<>();
Class<? extends Throwable>[] expectedExInner = expectedExceptions == null ? new Class[] {} : expectedExceptions;
Collections.addAll(expected, expectedExInner);
failsafe.onComplete(setCompletedEventFn);
Runnable postTestFn = () -> {
ignoreExceptions(() -> completionListenerWaiter.await(5000));
ExecutionCompletedEvent<Response> completedEvent = completedEventRef.get();
if (expectedExceptions == null) {
assertEquals(completedEvent.getResult().code(), expectedStatus);
assertNull(completedEvent.getException());
} else {
assertNull(completedEvent.getResult());
assertMatches(completedEvent.getException(), expectedExceptions);
}
if (then != null)
then.accept(futureRef.get(), completedEvent);
};
Consumer<Response> assertResult = response -> {
String result = unwrapExceptions(() -> response.body().string());
assertEquals(result, expectedResult);
assertEquals(response.code(), expectedStatus);
};
// Run sync test and assert result
System.out.println("\nRunning sync test");
FailsafeCall failsafeCall = FailsafeCall.with(failsafe).compose(when);
if (expectedExceptions == null) {
assertResult.accept(unwrapExceptions(failsafeCall::execute));
} else {
assertThrows(failsafeCall::execute, expectedExceptions);
}
postTestFn.run();
if (expectedExInner.length > 0)
expected.add(0, ExecutionException.class);
// Run async test and assert result
System.out.println("\nRunning async test");
failsafeCall = failsafeCall.clone();
CompletableFuture<Response> future = failsafeCall.executeAsync();
futureRef.set(future);
if (expectedExInner.length == 0) {
assertResult.accept(unwrapExceptions(future::get));
} else {
assertThrowsSup(future::get, expected);
}
postTestFn.run();
}
use of okhttp3.EventListener in project BestPracticeApp by pop1234o.
the class MainActivity method requestOkHttpGet.
/**
* ==============================
* 先用Builder模式来构建Request对象,然后将Request封装成一个Call(RealCall)对象
* 调用RealCall.execute。里面使用OkHttpClient.Dispatcher.execute(call)
* 里面将call加入Dispatcher中ArrayDeque中,然后再 RealCall.getResponseWithInterceptorChain()
* 中创建各种拦截器,(
* BridgeInterceptor 添加请求头,比如User-Agent,Connection,Host
* CacheInterceptor请求头缓存设置,
* ConnectInterceptor获取http连接,判断是1.0还是1.1,
* 获取到HttpCodec对象,真正建立起了Socket连接
* CallServerInterceptor 将请求行,请求头写入Socket,然后发送到服务端,接收Socket响应
* 这里用的是BufferedSource 是okio,NIO,然后获取到http响应,解析响应行,响应头,响应体
* 用ResponseBuilder来创建一个Response,然后返回
* )
* 以上是一个同步的过程,异步的过程类似,就是创建一个AsyncCall然后用线程池执行
* 返回Response后调用回调方法回调都是在子线程。
* =================================
* 他的巧妙的结构在于 ,链式的调用结构
* Response r = chain.proceed(request);
*
* Interceptor=>
* Response intercept(Chain chain){
* //处理Request
* Response r = chain.proceed(chain.request());
* //处理Response
* return r;
* }
*
* Chain=>中方法
* Response proceed(Request request){
* //这里主要遍历取出拦截器
* Response r = interceptors.get(index++).intercept(new Chain());
* return r;
* }
*
* ==============================
* 使用builder模式创建Request,OkHttpClient
* 使用工厂模式创建 EventListener
* 策略模式,设置拦截器
*/
private void requestOkHttpGet() {
new Thread(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void run() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
okhttp3.Request.Builder builder = new okhttp3.Request.Builder();
okhttp3.Request request = builder.url("http://www.google.com").build();
// 必须在这定义 // try-with-resources
try (okhttp3.Response response = okHttpClient.newCall(request).execute()) {
// try-with-resources
// 回调形式
// okHttpClient.newCall(request).enqueue(new Callback() {
// @Override
// public void onFailure(okhttp3.Call call, IOException e) {
//
// }
//
// @Override
// public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
//
// }
// });
// 注意这里是string()不是toString();
String s = response.body().string();
Log.i(TAG, "requestOkHttpGet: " + s);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Aggregations