Search in sources :

Example 41 with OkHttpClient

use of okhttp3.OkHttpClient in project couchbase-lite-android by couchbase.

the class ReplicatorWithSyncGatewayDBTest method sendRequestToEndpoint.

JSONObject sendRequestToEndpoint(URLEndpoint endpoint, String method, String path, String mediaType, byte[] body) throws Exception {
    URI endpointURI = endpoint.getURL();
    String _scheme = endpointURI.getScheme().equals(URLEndpoint.kURLEndpointTLSScheme) ? "https" : "http";
    String _host = endpointURI.getHost();
    int _port = endpointURI.getPort() + 1;
    path = (path != null) ? (path.startsWith("/") ? path : "/" + path) : "";
    String _path = String.format(Locale.ENGLISH, "%s%s", endpointURI.getPath(), path);
    URI uri = new URI(_scheme, null, _host, _port, _path, null, null);
    OkHttpClient client = new OkHttpClient();
    okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(uri.toURL());
    RequestBody requestBody = null;
    if (body != null && body instanceof byte[])
        requestBody = RequestBody.create(MediaType.parse(mediaType), body);
    builder.method(method, requestBody);
    okhttp3.Request request = builder.build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        Log.i(TAG, "Send request succeeded; URL=<%s>, Method=<%s>, Status=%d", uri, method, response.code());
        return new JSONObject(response.body().string());
    } else {
        // error
        Log.e(TAG, "Failed to send request; URL=<%s>, Method=<%s>, Status=%d, Error=%s", uri, method, response.code(), response.message());
        return null;
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) URI(java.net.URI) RequestBody(okhttp3.RequestBody)

Example 42 with OkHttpClient

use of okhttp3.OkHttpClient in project couchbase-lite-android by couchbase.

the class ReplicatorWithSyncGatewayTest method getSessionAuthenticatorFromSG.

SessionAuthenticator getSessionAuthenticatorFromSG() throws Exception {
    // Obtain Sync-Gateway Session ID
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    String url = String.format(Locale.ENGLISH, "http://%s:4985/seekrit/_session", config.remoteHost());
    RequestBody body = RequestBody.create(JSON, "{\"name\": \"pupshaw\"}");
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = client.newCall(request).execute();
    String respBody = response.body().string();
    Log.e(TAG, "json string -> " + respBody);
    JSONObject json = new JSONObject(respBody);
    return new SessionAuthenticator(json.getString("session_id"), json.getString("cookie_name"));
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 43 with OkHttpClient

use of okhttp3.OkHttpClient in project couchbase-lite-android by couchbase.

the class CBLWebSocket method setupOkHttpClient.

// -------------------------------------------------------------------------
// private methods
// -------------------------------------------------------------------------
private OkHttpClient setupOkHttpClient() throws GeneralSecurityException {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // timeouts
    builder.connectTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS);
    // redirection
    builder.followRedirects(true).followSslRedirects(true);
    // authenticator
    Authenticator authenticator = setupAuthenticator();
    if (authenticator != null)
        builder.authenticator(authenticator);
    // trusted certificate (pinned certificate)
    setupTrustedCertificate(builder);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Authenticator(okhttp3.Authenticator)

Example 44 with OkHttpClient

use of okhttp3.OkHttpClient in project BBS-Android by bdpqchen.

the class RxDoHttpClient method getUnsafeOkHttpClient.

public static OkHttpClient.Builder getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        okHttpClient.sslSocketFactory(sslSocketFactory);
        okHttpClient.protocols(Collections.singletonList(Protocol.HTTP_1_1));
        okHttpClient.hostnameVerifier((hostname, session) -> true);
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 45 with OkHttpClient

use of okhttp3.OkHttpClient in project bitcoin-wallet by bitcoin-wallet.

the class DynamicFeeLoader method fetchDynamicFees.

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile, final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();
    final Request.Builder request = new Request.Builder();
    request.url(url);
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));
    OkHttpClient.Builder httpClientBuilder = Constants.HTTP_CLIENT.newBuilder();
    httpClientBuilder.connectTimeout(5, TimeUnit.SECONDS);
    httpClientBuilder.writeTimeout(5, TimeUnit.SECONDS);
    httpClientBuilder.readTimeout(5, TimeUnit.SECONDS);
    final OkHttpClient httpClient = httpClientBuilder.build();
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Stopwatch(com.google.common.base.Stopwatch) Request(okhttp3.Request) HttpDate(okhttp3.internal.http.HttpDate) Date(java.util.Date) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) FileOutputStream(java.io.FileOutputStream)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)632 Request (okhttp3.Request)359 Response (okhttp3.Response)302 IOException (java.io.IOException)196 Test (org.junit.Test)155 Call (okhttp3.Call)111 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)67 Retrofit (retrofit2.Retrofit)65 File (java.io.File)56 Interceptor (okhttp3.Interceptor)45 RequestBody (okhttp3.RequestBody)39 ResponseBody (okhttp3.ResponseBody)38 Cache (okhttp3.Cache)36 Gson (com.google.gson.Gson)33 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)33 Headers (okhttp3.Headers)33 Callback (okhttp3.Callback)32 GsonBuilder (com.google.gson.GsonBuilder)29 JSONObject (org.json.JSONObject)28 Provides (dagger.Provides)27