Search in sources :

Example 16 with Route

use of okhttp3.Route in project sonarqube by SonarSource.

the class OkHttpClientBuilder method build.

public OkHttpClient build() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.proxy(proxy);
    if (connectTimeoutMs >= 0) {
        builder.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS);
    }
    if (readTimeoutMs >= 0) {
        builder.readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS);
    }
    builder.addNetworkInterceptor(this::addHeaders);
    if (proxyLogin != null) {
        builder.proxyAuthenticator((route, response) -> {
            if (response.request().header(PROXY_AUTHORIZATION) != null) {
                // Give up, we've already attempted to authenticate.
                return null;
            }
            if (HttpURLConnection.HTTP_PROXY_AUTH == response.code()) {
                String credential = Credentials.basic(proxyLogin, nullToEmpty(proxyPassword), UTF_8);
                return response.request().newBuilder().header(PROXY_AUTHORIZATION, credential).build();
            }
            return null;
        });
    }
    if (followRedirects != null) {
        builder.followRedirects(followRedirects);
        builder.followSslRedirects(followRedirects);
    }
    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions().allEnabledCipherSuites().supportsTlsExtensions(true).build();
    builder.connectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    X509TrustManager trustManager = sslTrustManager != null ? sslTrustManager : systemDefaultTrustManager();
    SSLSocketFactory sslFactory = sslSocketFactory != null ? sslSocketFactory : systemDefaultSslSocketFactory(trustManager);
    builder.sslSocketFactory(sslFactory, trustManager);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 17 with Route

use of okhttp3.Route in project FlareBot by FlareBot.

the class ApiRequester method getRequest.

private static Request getRequest(ApiRoute route, String bodyContent, MediaType type, boolean compressed) {
    Request.Builder request = new Request.Builder().url(route.getFullUrl());
    request.addHeader("Authorization", FlareBot.instance().getApiKey());
    request.addHeader("User-Agent", "Mozilla/5.0 FlareBot");
    RequestBody body = RequestBody.create(JSON, bodyContent);
    if (compressed && !bodyContent.isEmpty()) {
        request.addHeader("Content-Encoding", "gzip");
        logger.debug("Starting compression: " + System.currentTimeMillis());
        byte[] output = new byte[100];
        Deflater deflater = new Deflater();
        deflater.setInput(bodyContent.getBytes());
        deflater.finish();
        deflater.deflate(output);
        deflater.end();
        logger.debug("Finished compression: " + System.currentTimeMillis());
        body = RequestBody.create(type, output);
    }
    logger.debug("Sending " + route.getRoute() + ", Type: " + type.toString() + ", Compressed: " + compressed);
    switch(route.getMethod()) {
        case GET:
            request = request.get();
            break;
        case PATCH:
            request = request.patch(body);
            break;
        case POST:
            request = request.post(body);
            break;
        case PUT:
            request = request.put(body);
            break;
        case DELETE:
            request = request.delete(body);
            break;
        default:
            throw new IllegalArgumentException("The route " + route.name() + " is using an unsupported method! Method: " + route.getMethod().name());
    }
    return request.build();
}
Also used : Deflater(java.util.zip.Deflater) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 18 with Route

use of okhttp3.Route in project brave by openzipkin.

the class ITHttpServer method routeBasedRequestNameIncludesPathPrefix.

private void routeBasedRequestNameIncludesPathPrefix(String prefix) throws IOException {
    Response request1 = get(prefix + "/1?foo");
    Response request2 = get(prefix + "/2?bar");
    // get() doesn't check the response, check to make sure the server didn't 500
    assertThat(request1.isSuccessful()).isTrue();
    assertThat(request2.isSuccessful()).isTrue();
    // Reading the route parameter from the response ensures the test endpoint is correct
    assertThat(request1.body().string()).isEqualTo("1");
    assertThat(request2.body().string()).isEqualTo("2");
    MutableSpan span1 = testSpanHandler.takeRemoteSpan(SERVER);
    MutableSpan span2 = testSpanHandler.takeRemoteSpan(SERVER);
    // verify that the path and url reflect the initial request (not a route expression)
    assertThat(span1.tags()).containsEntry("http.method", "GET").containsEntry("http.path", prefix + "/1").containsEntry("http.url", url(prefix + "/1?foo"));
    assertThat(span2.tags()).containsEntry("http.method", "GET").containsEntry("http.path", prefix + "/2").containsEntry("http.url", url(prefix + "/2?bar"));
    // We don't know the exact format of the http route as it is framework specific
    // However, we know that it should match both requests and include the common part of the path
    Set<String> routeBasedNames = new LinkedHashSet<>(Arrays.asList(span1.name(), span2.name()));
    assertThat(routeBasedNames).hasSize(1);
    assertThat(routeBasedNames.iterator().next()).startsWith("GET " + prefix).doesNotEndWith(// no trailing slashes
    "/").doesNotContain(// no duplicate slashes
    "//");
}
Also used : Response(okhttp3.Response) LinkedHashSet(java.util.LinkedHashSet) MutableSpan(brave.handler.MutableSpan)

Example 19 with Route

use of okhttp3.Route in project openhab-android by openhab.

the class MjpegStreamer method httpRequest.

public InputStream httpRequest(String url, final String usr, final String pwd) {
    Request request = new Request.Builder().url(url).build();
    OkHttpClient client = new OkHttpClient.Builder().authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            Log.d(TAG, "Authenticating for response: " + response);
            Log.d(TAG, "Challenges: " + response.challenges());
            // Get username/password from preferences
            String credential = Credentials.basic(usr, pwd);
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    }).build();
    try {
        Log.d(TAG, "1. Sending http request");
        Response response = client.newCall(request).execute();
        Log.d(TAG, "2. Request finished, status = " + response.code());
        if (response.code() == 401) {
            // You must turn off camera User Access Control before this will work
            return null;
        }
        return response.body().byteStream();
    } catch (IOException e) {
        Log.e(TAG, "Request failed-IOException", e);
    // Error connecting to camera
    }
    return null;
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 20 with Route

use of okhttp3.Route in project hub-fortify-ssc-integration-service by blackducksoftware.

the class FortifyService method getHeader.

public static Builder getHeader(final PropertyConstants propertyConstants, final String token) {
    final HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    if (propertyConstants.getLogLevel().equalsIgnoreCase("INFO")) {
        logging.setLevel(Level.BASIC);
    } else {
        logging.setLevel(Level.BODY);
    }
    final OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
    okBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(final Route route, final Response response) throws IOException {
            if (token.equals(response.request().header("Authorization"))) {
                try {
                    FortifyExceptionUtil.verifyFortifyResponseCode(response.code(), "Unauthorized access of Fortify Api");
                } catch (final IntegrationException e) {
                    throw new IOException(e);
                }
                return null;
            }
            return response.request().newBuilder().header("Authorization", token).build();
        }
    });
    okBuilder.addInterceptor(logging);
    return okBuilder;
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) IntegrationException(com.blackducksoftware.integration.exception.IntegrationException) Builder(okhttp3.OkHttpClient.Builder) Request(okhttp3.Request) IOException(java.io.IOException) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Aggregations

Response (okhttp3.Response)52 Request (okhttp3.Request)41 IOException (java.io.IOException)40 OkHttpClient (okhttp3.OkHttpClient)33 Route (okhttp3.Route)31 Proxy (java.net.Proxy)23 InetSocketAddress (java.net.InetSocketAddress)21 Authenticator (okhttp3.Authenticator)18 Test (org.junit.Test)17 Map (java.util.Map)16 List (java.util.List)13 HttpUrl (okhttp3.HttpUrl)13 RequestBody (okhttp3.RequestBody)13 Test (org.junit.jupiter.api.Test)13 Credentials (okhttp3.Credentials)11 ArrayList (java.util.ArrayList)10 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)10 File (java.io.File)9 URI (java.net.URI)9 URL (java.net.URL)9