Example usage for com.squareup.okhttp Response request

List of usage examples for com.squareup.okhttp Response request

Introduction

In this page you can find the example usage for com.squareup.okhttp Response request.

Prototype

Request request

To view the source code for com.squareup.okhttp Response request.

Click Source Link

Usage

From source file:io.fabric8.devops.connector.DevOpsConnector.java

License:Apache License

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    final String username = Strings.isNullOrBlank(gerritUser) ? "admin" : gerritUser;
    final String password = Strings.isNullOrBlank(gerritPwd) ? "secret" : gerritPwd;

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);//from ww  w.j  a  va2 s.c  o  m
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;

    OkHttpClient client = new OkHttpClient();
    if (isNotNullOrEmpty(gerritUser) && isNotNullOrEmpty(gerritPwd)) {
        client.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                List<Challenge> challenges = response.challenges();
                Request request = response.request();
                for (int i = 0, size = challenges.size(); i < size; i++) {
                    Challenge challenge = challenges.get(i);
                    if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                        continue;

                    String credential = Credentials.basic(username, password);
                    return request.newBuilder().header("Authorization", credential).build();
                }
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    System.out.println("Requesting : " + GERRIT_URL);

    try {
        CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
        createRepoDTO.setDescription(gerritGitRepoDescription);
        createRepoDTO.setName(repoName);
        createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

        RequestBody body = RequestBody.create(JSON, MAPPER.writeValueAsString(createRepoDTO));
        Request request = new Request.Builder().post(body).url(GERRIT_URL).build();
        Response response = client.newCall(request).execute();
        System.out.println("responseBody : " + response.body().string());

    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
}

From source file:io.fabric8.docker.client.impl.EventHandle.java

License:Apache License

@Override
public void onResponse(Response r) throws IOException {
    response.set(r);/*from w  w w . j  a v a  2 s  .  c o  m*/
    if (r.code() == 200) {
        InputStreamPumper pumper = new InputStreamPumper(r.body().byteStream(), new Callback<byte[], Void>() {
            @Override
            public Void call(byte[] data) {
                onEvent(new String(data));
                return null;
            }
        }, new Callback<Boolean, Void>() {
            @Override
            public Void call(Boolean success) {
                if (success) {
                    if (succeded.compareAndSet(false, true) && !failed.get()) {
                        listener.onSuccess("Done.");
                    }
                } else {
                    if (failed.compareAndSet(false, true)) {
                        listener.onError("Failed.");
                    }
                }
                return null;
            }
        });
        closeables.add(pumper);
        executorService.submit(pumper);
    } else {
        onFailure(r.request(), new IOException(r.body().string()));
    }
    latch.countDown();
}

From source file:io.fabric8.docker.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {//from   ww  w.j  ava2  s.  c om
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {//  ww w  .ja  va2 s  .c  o m
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

From source file:io.jawg.osmcontributor.rest.utils.AuthenticationRequestInterceptor.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    Map<String, String> oAuthParams = loginPreferences.retrieveOAuthParams();

    if (oAuthParams != null) {
        Request originalRequest = response.request();
        String requestUrl = originalRequest.urlString();

        OAuthRequest oAuthRequest = new OAuthRequest(oAuthParams.get(CONSUMER_PARAM),
                oAuthParams.get(CONSUMER_SECRET_PARAM));
        oAuthRequest/*  w  ww  .j  a  v  a  2 s .c  o m*/
                .initParam(OAuthParams.getOAuthParams().put(TOKEN_PARAM, oAuthParams.get(TOKEN_PARAM)).toMap());
        oAuthRequest.setOAuthToken(oAuthParams.get(TOKEN_PARAM));
        oAuthRequest.setOAuthTokenSecret(oAuthParams.get(TOKEN_SECRET_PARAM));
        oAuthRequest.setRequestUrl(requestUrl);
        oAuthRequest.signRequest(Verb.valueOf(originalRequest.method()));
        oAuthRequest.encodeParams();

        Request.Builder finalRequest = originalRequest.newBuilder().header("Accept", "text/xml")
                .header("Authorization", oAuthRequest.getOAuthHeader())
                .method(originalRequest.method(), originalRequest.body());
        return finalRequest.build();
    } else {
        // create Base64 encoded string
        String authorization = "Basic " + Base64.encodeToString(
                (loginPreferences.retrieveLogin() + ":" + loginPreferences.retrievePassword()).getBytes(),
                Base64.NO_WRAP);
        return response.request().newBuilder().header("Authorization", authorization)
                .header("Accept", "text/xml").build();
    }
}

From source file:io.morea.handy.android.SendLogTask.java

License:Apache License

public SendLogTask(final Context context, final EventReporterConfiguration configuration) {
    // Don't make Context a WeakReference, otherwise the reference could get collected before the task is actually
    // run and the task should be executed in any case. There's also no risk to create a memory leak here because
    // the task will be thrown away afterwards anyway.
    this.context = context;
    this.configuration = configuration;

    client = new OkHttpClient();
    client.setConnectTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setWriteTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setAuthenticator(new Authenticator() {
        @Override//from   ww  w  .ja  v a  2s . c  o  m
        public Request authenticate(Proxy proxy, Response response) {
            String credential = Credentials.basic(configuration.getProbeId(), configuration.getAccessKey());
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) {
            return null;
        }
    });

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    this.gson = gsonBuilder.create();
}

From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }/*ww w  .j a va 2 s . c  o  m*/

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    UUID requestId = UUID.randomUUID();
    StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n')
            .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol);
    if (!logHeaders && requestBody != null) {
        requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)");
    }
    requestMessage.append('\n');

    if (logHeaders) {
        if (requestBody != null) {
            // Request body headers are only present when installed as a
            // network interceptor. Force
            // them to be included (when available) so there values are
            // known.
            if (requestBody.contentType() != null) {
                requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n');
            }
            if (requestBody.contentLength() != -1) {
                requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n');
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name)
                    || "Proxy-Authorization".equalsIgnoreCase(name)
                    || "WWW-Authenticate".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": *****\n");
            }
            // Skip headers from the request body as they are explicitly
            // logged above.
            else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": ").append(headers.value(i)).append('\n');
            }
        }

        if (!logBody || requestBody == null) {
            requestMessage.append("--> END ").append(requestId).append('\n');
        } else if (bodyEncoded(request.headers())) {
            requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n');
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            requestMessage.append('\n');
            if (isPlaintext(buffer)) {
                requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId)
                        .append(" (").append(requestBody.contentLength()).append("-byte body)\n");
            } else {
                requestMessage.append("--> END ").append(requestId).append(" (binary ")
                        .append(requestBody.contentLength()).append("-byte body omitted)\n");
            }
        }
    }

    logger.log(requestMessage.substring(0, requestMessage.length() - 1));

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- " + requestId + "HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ')
            .append(response.request().url()).append(" (").append(tookMs).append("ms");
    if (!logHeaders) {
        responseMessage.append(", ");
        if (contentLength != -1) {
            responseMessage.append(contentLength).append("-byte");
        } else {
            responseMessage.append("unknown-length");
        }
        responseMessage.append(" body");
    }
    responseMessage.append(")\n");

    responseMessage.append(response.code()).append(' ').append(response.message()).append('\n');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n');
        }

        if (!logBody || !HttpEngine.hasBody(response)) {
            responseMessage.append("<-- END HTTP\n");
        } else if (bodyEncoded(response.headers())) {
            responseMessage.append("<-- END HTTP (encoded body omitted)\n");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (!isPlaintext(buffer)) {
                responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size())
                        .append("-byte body omitted)");
                logger.log(responseMessage.toString());
                return response;
            }

            if (contentLength != 0) {
                responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n');
            }

            responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n");
        }
    }

    logger.log(responseMessage.substring(0, responseMessage.length() - 1));
    return response;
}

From source file:net.codestory.rest.RestAssert.java

License:Apache License

public RestAssert withAuthentication(String login, String password) {
    return withClient(setAuthenticator(new Authenticator() {
        AtomicInteger tries = new AtomicInteger(0);

        @Override/* w  w  w . j ava2 s . c om*/
        public Request authenticate(Proxy proxy, com.squareup.okhttp.Response response) {
            if (tries.getAndIncrement() > 0) {
                return null;
            }
            return addBasicAuthHeader(login, password).apply(response.request().newBuilder()).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, com.squareup.okhttp.Response response) {
            return null;
        }
    }));
}

From source file:net.goldenspiral.fetlifeoss.rest.interceptors.LoggingInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    if (enabled) {
        Log.i(TAG, String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
                request.headers()));/*from www.ja v  a  2 s  . c  om*/
    }

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    if (enabled) {
        Log.i(TAG, String.format("Received response for %s in %.1fms%n%s", response.request().url(),
                (t2 - t1) / 1e6d, response.headers()));
    }

    return response;
}

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

/**
 * ============Delivery============//from w ww  . java 2s.com
 */
protected void deliveryAsyncResult(Request request, HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    Util.log("Headers:\n" + request.headers().toString());

    final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback;

    //Call start
    callStart(resCallBack, request);

    mOkHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            Util.log("onFailure:" + request.toString());
            callFailure(resCallBack, request, null, e);
            callFinish(resCallBack);
        }

        @Override
        public void onResponse(final Response response) {
            try {
                Object ret = null;
                final String string = response.body().string();
                final boolean haveValue = !TextUtils.isEmpty(string);

                Util.log("onResponse:Code:%d Body:%s.", response.code(), (haveValue ? string : "null"));

                if (haveValue) {
                    ret = mResolver.analysis(string, resCallBack.getClass());
                }

                callSuccess(resCallBack, ret, response.code());
            } catch (Exception e) {
                Util.log("onResponse Failure:" + response.request().toString());
                callFailure(resCallBack, response.request(), response, e);
            }
            callFinish(resCallBack);
        }
    });
}