Example usage for com.squareup.okhttp Request url

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

Introduction

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

Prototype

HttpUrl url

To view the source code for com.squareup.okhttp Request url.

Click Source Link

Usage

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

/**
 * This test puts a request in front of one that is to be canceled, so that it is canceled before
 * I/O takes place./*from ww w  .j a v a 2  s  .co m*/
 */
@Test
public void canceledBeforeIOSignalsOnFailure() throws Exception {
    client.getDispatcher().setMaxRequests(1); // Force requests to be executed serially.
    server.get().setDispatcher(new Dispatcher() {
        char nextResponse = 'A';

        @Override
        public MockResponse dispatch(RecordedRequest request) {
            client.cancel("request B");
            return new MockResponse().setBody(Character.toString(nextResponse++));
        }
    });

    Request requestA = new Request.Builder().url(server.getUrl("/a")).tag("request A").build();
    client.newCall(requestA).enqueue(callback);
    assertEquals("/a", server.takeRequest().getPath());

    Request requestB = new Request.Builder().url(server.getUrl("/b")).tag("request B").build();
    client.newCall(requestB).enqueue(callback);

    callback.await(requestA.url()).assertBody("A");
    // At this point we know the callback is ready, and that it will receive a cancel failure.
    callback.await(requestB.url()).assertFailure("Canceled");
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
    Request requestA = new Request.Builder().url(server.getUrl("/a")).tag("request A").build();
    final Call call = client.newCall(requestA);
    server.get().setDispatcher(new Dispatcher() {
        @Override//from  www.  j a va2s.  co m
        public MockResponse dispatch(RecordedRequest request) {
            call.cancel();
            return new MockResponse().setBody("A");
        }
    });

    call.enqueue(callback);
    assertEquals("/a", server.takeRequest().getPath());

    callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL", "Socket closed");
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void asyncInterceptors(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override//from  w w  w.  j  a  va  2s  .  c o  m
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().addHeader("OkHttp-Intercepted", "yep").build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    client.newCall(request).enqueue(callback);

    callback.await(request.url()).assertCode(200).assertHeader("OkHttp-Intercepted", "yep");
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

/** Make sure interceptors can interact with the OkHttp client asynchronously. */
@Test//from   w  w w  . ja  v a 2 s . c  om
public void interceptorMakesAnUnrelatedAsyncRequest() throws Exception {
    server.enqueue(new MockResponse().setBody("a")); // Fetched by interceptor.
    server.enqueue(new MockResponse().setBody("b")); // Fetched directly.

    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain.request().url().getPath().equals("/b")) {
                Request requestA = new Request.Builder().url(server.getUrl("/a")).build();

                try {
                    RecordingCallback callbackA = new RecordingCallback();
                    client.newCall(requestA).enqueue(callbackA);
                    callbackA.await(requestA.url()).assertBody("a");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return chain.proceed(chain.request());
        }
    });

    Request requestB = new Request.Builder().url(server.getUrl("/b")).build();
    RecordingCallback callbackB = new RecordingCallback();
    client.newCall(requestB).enqueue(callbackB);
    callbackB.await(requestB.url()).assertBody("b");
}

From source file:com.carlospinan.demoretrofit2.helpers.LoggingInterceptor.java

License:Open Source License

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

    long t1 = System.nanoTime();
    Log.d(LOG_TAG, String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(),
            request.headers()));/*from  www.jav a2s  . c om*/

    Buffer requestBuffer = new Buffer();
    if (request.body() != null) {
        request.body().writeTo(requestBuffer);
        Log.d(LOG_TAG, requestBuffer.readUtf8());
    }

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Log.d(LOG_TAG, String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(),
            (t2 - t1) / 1e6d, response.headers()));

    MediaType contentType = response.body().contentType();
    String content = response.body().string();
    Log.d(LOG_TAG, content);

    ResponseBody wrappedBody = ResponseBody.create(contentType, content);
    return response.newBuilder().body(wrappedBody).build();
}

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   www. j  ava2  s .c om*/
    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.cml.rx.android.api.HttpLoggingInterceptor.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.  jav  a  2  s  .  c  o  m

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

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();

    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        if (hasRequestBody) {
            // 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) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly
            // logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

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

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

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

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (!logBody || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } 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) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    logger.log("");
                    logger.log("Couldn't decode the response body; charset is likely malformed.");
                    logger.log("<-- END HTTP");

                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }

    return response;
}

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

License:Apache License

@Test
public void testFetchUrl() throws Exception {
    final URL url = new URL("http://localhost:8080");
    final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
    HttpArtifactCache cache = new HttpArtifactCache(null, null, new URL("http://localhost:8080"),
            /* doStore */ true, new FakeProjectFilesystem(), HASH_FUNCTION) {
        @Override//from   w  w w.j  a  v a 2  s.co  m
        protected Response fetchCall(Request request) throws IOException {
            assertEquals(new URL(url, "artifact/key/" + ruleKey.toString()), request.url());
            return new Response.Builder().code(HttpURLConnection.HTTP_OK).protocol(Protocol.HTTP_1_1)
                    .request(request).body(createBody("data")).build();
        }
    };
    cache.fetch(ruleKey, new File("output/file"));
    cache.close();
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private com.squareup.okhttp.Request buildReq(Request request) {
    return new com.squareup.okhttp.Request.Builder().method(request.method().toString(), buildReqBody(request))
            .headers(Headers.of(request.headers())).url(request.url()).build();
}

From source file:com.github.drrb.surefiresplitter.go.GoServer.java

License:Open Source License

private Response execute(Request request) throws CommunicationError {
    System.out.println(" -> " + request.url());
    try {// w  w  w .j a v  a  2  s  .c o m
        Response response = httpClient.newCall(request).execute();
        System.out.println(" <- " + response.code() + ": " + response.message() + " ("
                + Bytes.render(response.body().contentLength()) + ")");
        return response;
    } catch (IOException e) {
        throw new CommunicationError("Connection to Go server failed", e);
    }
}