Example usage for com.squareup.okhttp Request uri

List of usage examples for com.squareup.okhttp Request uri

Introduction

In this page you can find the example usage for com.squareup.okhttp Request uri.

Prototype

public URI uri() throws IOException 

Source Link

Usage

From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {

    OkHttpClient requestScopedClient = clientSupplier.get();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));
    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();

    // Check for Artifactory header and init potential file for downstream use
    File destinationFile = null;/*from   ww  w  . j  av a2s . com*/
    String artFileName = responseHeaders.get("X-Artifactory-Filename");
    if (artFileName != null) {

        GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(),
                endpoint.get().toURL());
        destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName,
                responseHeaders.get("ETag"));
        headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath());
    }

    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        if (destinationFile != null) {
            if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) {
                InputStream inputStream = null;
                try {
                    inputStream = response.body().byteStream();
                    ArtifactoryUtils.resolveInputStream(inputStream, destinationFile);
                } catch (Exception e) {
                    Throwables.propagate(e);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
            IOUtils.closeQuietly(response.body().byteStream());
        } else {
            Payload payload = newInputStreamPayload(response.body().byteStream());
            contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
            builder.payload(payload);
        }
    }

    builder.headers(filterOutContentHeaders(headers));
    return builder.build();
}

From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java

License:Apache License

@Test
public void testFetchUrl() throws Exception {
    final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
    final String expectedUri = "http://localhost:8080/artifacts/key/00000000000000000000000000000000";

    HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"),
            /* doStore */ true, new FakeProjectFilesystem(), BUCK_EVENT_BUS) {
        @Override/*www.  jav  a  2s  . co  m*/
        protected Response fetchCall(Request request) throws IOException {
            assertEquals(expectedUri, request.uri().toString());
            return new Response.Builder().request(request).protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK).body(createResponseBody(ImmutableSet.of(ruleKey),
                            ImmutableMap.<String, String>of(), ByteSource.wrap(new byte[0]), "data"))
                    .build();
        }
    };
    cache.fetch(ruleKey, Paths.get("output/file"));
    cache.close();
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody,
        String method) {//w ww.  j a  v a  2  s  .c  o m
    String uri = null;
    long waitTime = 0L;
    try {
        setHeaders(request, builder, request.getHeaderInformation());

        List<String> cookies = new ArrayList<String>();
        if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) {
            for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore()
                    .getCookies()) {
                cookies.add("REQUEST COOKIE: " + httpCookie.toString());
            }
        }

        Request okRequest = builder.build();
        uri = okRequest.uri().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + okRequest.method() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies,
                false);

        Response response = okHttpClient.newCall(okRequest).execute();
        long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));
        long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.code() != 203 && response.code() != 202 && response.code() != 204) {
            try {
                responseBody = response.body().bytes();
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }

        processResponse(responseBody, startTime, endTime, request, response.message(), response.code(),
                response.headers());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method + " to url " + uri + " |  error: " + ex.toString(), LogEventType.IO),
                ex);
        throw new RuntimeException(ex);
    } finally {
        if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.liferay.mobile.android.auth.basic.DigestAuthentication.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {

    Request request = response.request();
    Builder builder = request.newBuilder();

    try {/*from  w  ww .j ava 2s  .  c o m*/
        BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE,
                response.header(Headers.WWW_AUTHENTICATE));

        DigestScheme scheme = new DigestScheme();
        scheme.processChallenge(authenticateHeader);

        BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue();

        builder.addHeader(Headers.AUTHORIZATION, authorizationHeader);
    } catch (Exception e) {
        throw new IOException(e);
    }

    return builder.build();
}

From source file:com.liferay.mobile.sdk.auth.DigestAuthentication.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {

    Request request = response.request();

    Builder builder = request.newBuilder();

    try {//from  w  ww . jav  a  2 s  .  co  m
        BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE,
                response.header(Headers.WWW_AUTHENTICATE));

        DigestScheme scheme = new DigestScheme();

        scheme.processChallenge(authenticateHeader);

        BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue();

        builder.addHeader(Headers.AUTHORIZATION, authorizationHeader);
    } catch (Exception e) {
        throw new IOException(e);
    }

    return builder.build();
}

From source file:com.spotify.apollo.http.client.HttpClient.java

License:Apache License

@Override
public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest,
        Optional<com.spotify.apollo.Request> apolloIncomingRequest) {

    final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> {
        final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse)
                .orElse(DEFAULT_CONTENT_TYPE);
        return RequestBody.create(contentType, payload);
    });//from  ww w. ja v  a 2s  . c  om

    Headers.Builder headersBuilder = new Headers.Builder();
    apolloRequest.headers().asMap().forEach((k, v) -> headersBuilder.add(k, v));

    apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER))
            .ifPresent(header -> headersBuilder.add(AUTHORIZATION_HEADER, header));

    final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null))
            .url(apolloRequest.uri()).headers(headersBuilder.build()).build();

    final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>();

    //https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
    OkHttpClient finalClient = client;
    if (apolloRequest.ttl().isPresent() && client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) {
        finalClient = client.clone();
        finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS);
    }

    finalClient.newCall(request).enqueue(TransformingCallback.create(result));

    return result;
}

From source file:com.spotify.apollo.http.server.HttpServerModuleTest.java

License:Apache License

@Test
public void testParsesQueryParameters() throws Exception {
    int port = 9084;

    try (Service.Instance instance = service().start(NO_ARGS, onPort(port))) {
        HttpServer server = HttpServerModule.server(instance);
        TestHandler testHandler = new TestHandler();
        server.start(testHandler);//from w  w  w.  j a va2s . c  o m

        Request httpRequest = new Request.Builder().get().url(baseUrl(port) + "/query?a=foo&b=bar&b=baz")
                .build();

        com.squareup.okhttp.Response response = okHttpClient.newCall(httpRequest).execute();
        assertThat(response.code(), is(IM_A_TEAPOT.code()));

        assertThat(testHandler.requests.size(), is(1));
        final com.spotify.apollo.Request apolloRequest = testHandler.requests.get(0).request();
        assertThat(apolloRequest.uri(), is("/query?a=foo&b=bar&b=baz"));
        assertThat(apolloRequest.parameter("a"), is(Optional.of("foo")));
        assertThat(apolloRequest.parameter("b"), is(Optional.of("bar")));
        assertThat(apolloRequest.parameters().get("b"), is(asList("bar", "baz")));
        assertThat(apolloRequest.parameter("c"), is(Optional.empty()));
    }
}

From source file:com.spotify.apollo.http.server.HttpServerModuleTest.java

License:Apache License

@Test
public void testParsesHeadersParameters() throws Exception {
    int port = 9085;

    try (Service.Instance instance = service().start(NO_ARGS, onPort(port))) {
        HttpServer server = HttpServerModule.server(instance);
        TestHandler testHandler = new TestHandler();
        server.start(testHandler);//w  w w .ja v  a2  s . c  o  m

        Request httpRequest = new Request.Builder().get().url(baseUrl(port) + "/headers")
                .addHeader("Foo", "bar").addHeader("Repeat", "once").addHeader("Repeat", "twice").build();

        com.squareup.okhttp.Response response = okHttpClient.newCall(httpRequest).execute();
        assertThat(response.code(), is(IM_A_TEAPOT.code()));

        assertThat(testHandler.requests.size(), is(1));
        final com.spotify.apollo.Request apolloRequest = testHandler.requests.get(0).request();
        assertThat(apolloRequest.uri(), is("/headers"));
        assertThat(apolloRequest.header("Foo"), is(Optional.of("bar")));
        assertThat(apolloRequest.header("Repeat"), is(Optional.of("once,twice")));
        assertThat(apolloRequest.header("Baz"), is(Optional.empty()));

        System.out.println("apolloRequest.headers() = " + apolloRequest.headers());
    }
}

From source file:dulleh.akhyou.Utils.CloudflareHttpClient.java

License:Open Source License

public Response execute(Request request) throws IOException, CloudflareException {
    Response resp = client.newCall(request).execute();
    String refresh = resp.header("Refresh");
    String server = resp.header("Server");

    List<HttpCookie> cookies = cookieManager.getCookieStore().get(request.uri());
    boolean hasCookie = Stream.of(cookies).anyMatch(c -> c.getName().equals("cf_clearance"));

    if (hasCookie)
        return resp;

    if (forceSolve) {
        return solveCloudflare(resp);
    } else if (refresh != null && refresh.contains("URL=/cdn-cgi/") && server != null
            && server.equals("cloudflare-nginx")) {

        //System.out.println("solving cloudflare");
        return solveCloudflare(resp);
    }//from www.  j ava  2  s . c  o  m

    return resp;
}

From source file:io.minio.RequestSigner.java

License:Apache License

private Request signV4(Request originalRequest, byte[] data)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, IOException {
    if (this.accessKey == null || this.secretKey == null) {
        return originalRequest;
    }/*from www. j a v  a2s . co  m*/

    String region = getRegion(originalRequest);
    byte[] dataHashBytes = computeSha256(data);
    String dataHash = DatatypeConverter.printHexBinary(dataHashBytes).toLowerCase();

    String host = originalRequest.uri().getHost();
    int port = originalRequest.uri().getPort();
    if (port != -1) {
        String scheme = originalRequest.uri().getScheme();
        if ("http".equals(scheme) && port != 80) {
            host += ":" + originalRequest.uri().getPort();
        } else if ("https".equals(scheme) && port != 443) {
            host += ":" + originalRequest.uri().getPort();
        }
    }

    Request signedRequest = originalRequest.newBuilder().header("x-amz-content-sha256", dataHash)
            .header("Host", host).build();

    // get signed headers
    String signedHeaders = getSignedHeaders(signedRequest);

    // get canonical request and headers to sign
    String canonicalRequest = getCanonicalRequest(signedRequest, dataHash, signedHeaders);

    // get sha256 of canonical request
    byte[] canonicalHashBytes = computeSha256(canonicalRequest.getBytes("UTF-8"));
    String canonicalHash = DatatypeConverter.printHexBinary(canonicalHashBytes).toLowerCase();

    // get key to sign
    String stringToSign = getStringToSign(region, canonicalHash, this.date);
    byte[] signingKey = getSigningKey(this.date, region, this.secretKey);

    // get signing key
    String signature = DatatypeConverter.printHexBinary(getSignature(signingKey, stringToSign)).toLowerCase();

    // get authorization header
    String authorization = getAuthorizationHeader(signedHeaders, signature, this.date, region);

    signedRequest = signedRequest.newBuilder().header("Authorization", authorization).build();

    return signedRequest;
}