Search in sources :

Example 56 with Headers

use of okhttp3.Headers in project okhttp by square.

the class SynchronousGet method run.

public void run() throws Exception {
    Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        Headers responseHeaders = response.headers();
        for (int i = 0; i < responseHeaders.size(); i++) {
            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }
        System.out.println(response.body().string());
    }
}
Also used : Response(okhttp3.Response) Headers(okhttp3.Headers) Request(okhttp3.Request) IOException(java.io.IOException)

Example 57 with Headers

use of okhttp3.Headers in project okhttp by square.

the class CallTest method proxyConnectOmitsApplicationHeaders.

/** Test which headers are sent unencrypted to the HTTP proxy. */
@Test
public void proxyConnectOmitsApplicationHeaders() throws Exception {
    server.useHttps(sslClient.socketFactory, true);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
    RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
    client = client.newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).proxy(server.toProxyAddress()).hostnameVerifier(hostnameVerifier).build();
    Request request = new Request.Builder().url("https://android.com/foo").header("Private", "Secret").header("User-Agent", "App 1.0").build();
    Response response = client.newCall(request).execute();
    assertEquals("encrypted response from the origin server", response.body().string());
    RecordedRequest connect = server.takeRequest();
    assertNull(connect.getHeader("Private"));
    assertEquals(Version.userAgent(), connect.getHeader("User-Agent"));
    assertEquals("Keep-Alive", connect.getHeader("Proxy-Connection"));
    assertEquals("android.com:443", connect.getHeader("Host"));
    RecordedRequest get = server.takeRequest();
    assertEquals("Secret", get.getHeader("Private"));
    assertEquals("App 1.0", get.getHeader("User-Agent"));
    assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 58 with Headers

use of okhttp3.Headers in project okhttp by square.

the class OkHttpURLConnection method getHeaders.

private Headers getHeaders() throws IOException {
    if (responseHeaders == null) {
        Response response = getResponse(true);
        Headers headers = response.headers();
        responseHeaders = headers.newBuilder().add(SELECTED_PROTOCOL, response.protocol().toString()).add(RESPONSE_SOURCE, responseSourceHeader(response)).build();
    }
    return responseHeaders;
}
Also used : Response(okhttp3.Response) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) JavaNetHeaders(okhttp3.internal.JavaNetHeaders)

Example 59 with Headers

use of okhttp3.Headers in project okhttp by square.

the class OkHttpURLConnection method buildCall.

private Call buildCall() throws IOException {
    if (call != null) {
        return call;
    }
    connected = true;
    if (doOutput) {
        if (method.equals("GET")) {
            // they are requesting a stream to write to. This implies a POST method
            method = "POST";
        } else if (!HttpMethod.permitsRequestBody(method)) {
            throw new ProtocolException(method + " does not support writing");
        }
    }
    if (requestHeaders.get("User-Agent") == null) {
        requestHeaders.add("User-Agent", defaultUserAgent());
    }
    OutputStreamRequestBody requestBody = null;
    if (HttpMethod.permitsRequestBody(method)) {
        // Add a content type for the request body, if one isn't already present.
        String contentType = requestHeaders.get("Content-Type");
        if (contentType == null) {
            contentType = "application/x-www-form-urlencoded";
            requestHeaders.add("Content-Type", contentType);
        }
        boolean stream = fixedContentLength != -1L || chunkLength > 0;
        long contentLength = -1L;
        String contentLengthString = requestHeaders.get("Content-Length");
        if (fixedContentLength != -1L) {
            contentLength = fixedContentLength;
        } else if (contentLengthString != null) {
            contentLength = Long.parseLong(contentLengthString);
        }
        requestBody = stream ? new StreamedRequestBody(contentLength) : new BufferedRequestBody(contentLength);
        requestBody.timeout().timeout(client.writeTimeoutMillis(), TimeUnit.MILLISECONDS);
    }
    Request request = new Request.Builder().url(Internal.instance.getHttpUrlChecked(getURL().toString())).headers(requestHeaders.build()).method(method, requestBody).build();
    if (urlFilter != null) {
        urlFilter.checkURLPermitted(request.url().url());
    }
    OkHttpClient.Builder clientBuilder = client.newBuilder();
    clientBuilder.interceptors().clear();
    clientBuilder.interceptors().add(UnexpectedException.INTERCEPTOR);
    clientBuilder.networkInterceptors().clear();
    clientBuilder.networkInterceptors().add(networkInterceptor);
    // Use a separate dispatcher so that limits aren't impacted. But use the same executor service!
    clientBuilder.dispatcher(new Dispatcher(client.dispatcher().executorService()));
    // If we're currently not using caches, make sure the engine's client doesn't have one.
    if (!getUseCaches()) {
        clientBuilder.cache(null);
    }
    return call = clientBuilder.build().newCall(request);
}
Also used : ProtocolException(java.net.ProtocolException) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Dispatcher(okhttp3.Dispatcher)

Example 60 with Headers

use of okhttp3.Headers in project okhttp by square.

the class UrlConnectionCacheTest method assertConditionallyCached.

/** @return the request with the conditional get headers. */
private RecordedRequest assertConditionallyCached(MockResponse response) throws Exception {
    // scenario 1: condition succeeds
    server.enqueue(response.setBody("A").setStatus("HTTP/1.1 200 A-OK"));
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    // scenario 2: condition fails
    server.enqueue(response.setBody("B").setStatus("HTTP/1.1 200 B-OK"));
    server.enqueue(new MockResponse().setStatus("HTTP/1.1 200 C-OK").setBody("C"));
    URL valid = server.url("/valid").url();
    HttpURLConnection connection1 = urlFactory.open(valid);
    assertEquals("A", readAscii(connection1));
    assertEquals(HttpURLConnection.HTTP_OK, connection1.getResponseCode());
    assertEquals("A-OK", connection1.getResponseMessage());
    HttpURLConnection connection2 = urlFactory.open(valid);
    assertEquals("A", readAscii(connection2));
    assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
    assertEquals("A-OK", connection2.getResponseMessage());
    URL invalid = server.url("/invalid").url();
    HttpURLConnection connection3 = urlFactory.open(invalid);
    assertEquals("B", readAscii(connection3));
    assertEquals(HttpURLConnection.HTTP_OK, connection3.getResponseCode());
    assertEquals("B-OK", connection3.getResponseMessage());
    HttpURLConnection connection4 = urlFactory.open(invalid);
    assertEquals("C", readAscii(connection4));
    assertEquals(HttpURLConnection.HTTP_OK, connection4.getResponseCode());
    assertEquals("C-OK", connection4.getResponseMessage());
    // regular get
    server.takeRequest();
    // conditional get
    return server.takeRequest();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)58 Response (okhttp3.Response)53 Headers (okhttp3.Headers)46 IOException (java.io.IOException)34 MockResponse (okhttp3.mockwebserver.MockResponse)33 HttpHeaders (okhttp3.internal.http.HttpHeaders)29 ResponseBody (okhttp3.ResponseBody)27 RequestBody (okhttp3.RequestBody)21 List (java.util.List)19 MediaType (okhttp3.MediaType)16 HashMap (java.util.HashMap)15 Map (java.util.Map)15 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Buffer (okio.Buffer)12 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11