Search in sources :

Example 16 with Dns

use of okhttp3.Dns in project okhttp by square.

the class LoggingEventListenerTest method dnsFail.

@Test
public void dnsFail() throws IOException {
    client = new OkHttpClient.Builder().dns(hostname -> {
        throw new UnknownHostException("reason");
    }).eventListenerFactory(loggingEventListenerFactory).build();
    try {
        client.newCall(request().build()).execute();
        fail();
    } catch (UnknownHostException expected) {
    }
    logRecorder.assertLogMatch("callStart: Request\\{method=GET, url=" + url + "\\}").assertLogMatch("proxySelectStart: " + url).assertLogMatch("proxySelectEnd: \\[DIRECT\\]").assertLogMatch("dnsStart: " + url.host()).assertLogMatch("callFailed: java.net.UnknownHostException: reason").assertNoMoreLogs();
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) BeforeEach(org.junit.jupiter.api.BeforeEach) HTTP_1_1(okhttp3.Protocol.HTTP_1_1) HTTP_2(okhttp3.Protocol.HTTP_2) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) MockWebServerExtension(mockwebserver3.junit5.internal.MockWebServerExtension) HandshakeCertificates(okhttp3.tls.HandshakeCertificates) MockWebServer(mockwebserver3.MockWebServer) RequestBody(okhttp3.RequestBody) SocketPolicy(mockwebserver3.SocketPolicy) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Arrays.asList(java.util.Arrays.asList) EventListener(okhttp3.EventListener) Response(okhttp3.Response) Call(okhttp3.Call) MediaType(okhttp3.MediaType) Request(okhttp3.Request) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OkHttpClientTestRule(okhttp3.OkHttpClientTestRule) Test(org.junit.jupiter.api.Test) TlsUtil.localhost(okhttp3.tls.internal.TlsUtil.localhost) OkHttpClient(okhttp3.OkHttpClient) PlatformRule(okhttp3.testing.PlatformRule) MockResponse(mockwebserver3.MockResponse) TestUtil(okhttp3.TestUtil) HttpUrl(okhttp3.HttpUrl) UnknownHostException(java.net.UnknownHostException) Test(org.junit.jupiter.api.Test)

Example 17 with Dns

use of okhttp3.Dns in project okhttp by square.

the class DnsOverHttpsTest method usesCache.

// TODO GET preferred order - with tests to confirm this
// 1. successful fresh cached GET response
// 2. unsuccessful (404, 500) fresh cached GET response
// 3. successful network response
// 4. successful stale cached GET response
// 5. unsuccessful response
// TODO how closely to follow POST rules on caching?
@Test
public void usesCache() throws Exception {
    Cache cache = new Cache(Path.get("cache"), 100 * 1024, cacheFs);
    OkHttpClient cachedClient = bootstrapClient.newBuilder().cache(cache).build();
    DnsOverHttps cachedDns = buildLocalhost(cachedClient, false);
    server.enqueue(dnsResponse("0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c00050001" + "00000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c04200010" + "0010000003b00049df00112").setHeader("cache-control", "private, max-age=298"));
    List<InetAddress> result = cachedDns.lookup("google.com");
    assertThat(result).containsExactly(address("157.240.1.18"));
    RecordedRequest recordedRequest = server.takeRequest();
    assertThat(recordedRequest.getMethod()).isEqualTo("GET");
    assertThat(recordedRequest.getPath()).isEqualTo("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ");
    result = cachedDns.lookup("google.com");
    assertThat(result).isEqualTo(singletonList(address("157.240.1.18")));
}
Also used : RecordedRequest(mockwebserver3.RecordedRequest) OkHttpClient(okhttp3.OkHttpClient) InetAddress(java.net.InetAddress) Cache(okhttp3.Cache) Test(org.junit.jupiter.api.Test)

Example 18 with Dns

use of okhttp3.Dns in project Signal-Android by WhisperSystems.

the class PushServiceSocket method createConnectionClient.

private static OkHttpClient createConnectionClient(SignalUrl url, List<Interceptor> interceptors, Optional<Dns> dns, Optional<SignalProxy> proxy) {
    try {
        TrustManager[] trustManagers = BlacklistingTrustManager.createFor(url.getTrustStore());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);
        OkHttpClient.Builder builder = new OkHttpClient.Builder().sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager) trustManagers[0]).connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS))).dns(dns.or(Dns.SYSTEM));
        if (proxy.isPresent()) {
            builder.socketFactory(new TlsProxySocketFactory(proxy.get().getHost(), proxy.get().getPort(), dns));
        }
        builder.sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager) trustManagers[0]).connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS))).build();
        builder.connectionPool(new ConnectionPool(5, 45, TimeUnit.SECONDS));
        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
        return builder.build();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}
Also used : ConnectionPool(okhttp3.ConnectionPool) OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) Tls12SocketFactory(org.whispersystems.signalservice.api.util.Tls12SocketFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) X509TrustManager(javax.net.ssl.X509TrustManager) BlacklistingTrustManager(org.whispersystems.signalservice.internal.util.BlacklistingTrustManager) TrustManager(javax.net.ssl.TrustManager) Interceptor(okhttp3.Interceptor) TlsProxySocketFactory(org.whispersystems.signalservice.api.util.TlsProxySocketFactory)

Example 19 with Dns

use of okhttp3.Dns in project Signal-Android by WhisperSystems.

the class WebSocketConnection method connect.

public synchronized Observable<WebSocketConnectionState> connect() {
    log("connect()");
    if (client == null) {
        String filledUri;
        if (credentialsProvider.isPresent()) {
            String identifier = Objects.requireNonNull(credentialsProvider.get().getAci()).toString();
            if (credentialsProvider.get().getDeviceId() != SignalServiceAddress.DEFAULT_DEVICE_ID) {
                identifier += "." + credentialsProvider.get().getDeviceId();
            }
            filledUri = String.format(wsUri, identifier, credentialsProvider.get().getPassword());
        } else {
            filledUri = wsUri;
        }
        Pair<SSLSocketFactory, X509TrustManager> socketFactory = createTlsSocketFactory(trustStore);
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().sslSocketFactory(new Tls12SocketFactory(socketFactory.first()), socketFactory.second()).connectionSpecs(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)).readTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS).dns(dns.or(Dns.SYSTEM)).connectTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS);
        for (Interceptor interceptor : interceptors) {
            clientBuilder.addInterceptor(interceptor);
        }
        if (signalProxy.isPresent()) {
            clientBuilder.socketFactory(new TlsProxySocketFactory(signalProxy.get().getHost(), signalProxy.get().getPort(), dns));
        }
        OkHttpClient okHttpClient = clientBuilder.build();
        Request.Builder requestBuilder = new Request.Builder().url(filledUri);
        if (signalAgent != null) {
            requestBuilder.addHeader("X-Signal-Agent", signalAgent);
        }
        webSocketState.onNext(WebSocketConnectionState.CONNECTING);
        this.client = okHttpClient.newWebSocket(requestBuilder.build(), this);
    }
    return webSocketState;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) Request(okhttp3.Request) ByteString(okio.ByteString) Tls12SocketFactory(org.whispersystems.signalservice.api.util.Tls12SocketFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(okhttp3.Interceptor) TlsProxySocketFactory(org.whispersystems.signalservice.api.util.TlsProxySocketFactory)

Example 20 with Dns

use of okhttp3.Dns in project AndLang by wugemu.

the class HttpU method newOkHttpClient.

public OkHttpClient newOkHttpClient() {
    HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
    logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    if (openDns) {
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).addNetworkInterceptor(// 添加网络请求日志
        logInterceptor).dns(new HttpDns()).build();
    } else if (openLog) {
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).addNetworkInterceptor(// 添加网络请求日志
        logInterceptor).build();
    } else if (BaseLangUtil.isHaveSDPer()) {
        // 开启本地存储权限后使用缓存机制
        // 新建一个cache,指定目录为外部目录下的okhttp_cache目录,大小为100M
        Cache cache = new Cache(PicSelUtil.getCacheDir(), 100 * 1024 * 1024);
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).cache(// 缓存设置
        cache).addInterceptor(// 请求网络拦截
        new RequestCacheI()).build();
    } else {
        // 新建一个cache,指定目录为外部目录下的okhttp_cache目录,大小为100M
        return // 设置读取超时时间
        new OkHttpClient.Builder().dispatcher(new Dispatcher(ExecutorServiceUtil.getInstence().getExecutorService())).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, // 设置写的超时时间
        TimeUnit.SECONDS).connectTimeout(20, // 设置连接超时时间
        TimeUnit.SECONDS).build();
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache)

Aggregations

Test (org.junit.Test)23 MockResponse (okhttp3.mockwebserver.MockResponse)13 OkHttpClient (okhttp3.OkHttpClient)12 DoubleInetAddressDns (okhttp3.internal.DoubleInetAddressDns)10 Test (org.junit.jupiter.api.Test)9 IOException (java.io.IOException)8 Request (okhttp3.Request)8 SingleInetAddressDns (okhttp3.internal.SingleInetAddressDns)8 InetAddress (java.net.InetAddress)7 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)7 MockResponse (mockwebserver3.MockResponse)6 Response (okhttp3.Response)6 HttpURLConnection (java.net.HttpURLConnection)5 InetSocketAddress (java.net.InetSocketAddress)5 UnknownHostException (java.net.UnknownHostException)5 List (java.util.List)4 X509TrustManager (javax.net.ssl.X509TrustManager)4 Dns (okhttp3.Dns)4 Interceptor (okhttp3.Interceptor)4 HandshakeCertificates (okhttp3.tls.HandshakeCertificates)4