Search in sources :

Example 76 with Headers

use of com.amazonaws.services.s3.Headers in project okhttp by square.

the class JavaApiConverter method createOkRequest.

/**
   * Creates an OkHttp {@link Request} from the supplied information.
   *
   * <p>This method allows a {@code null} value for {@code requestHeaders} for situations where a
   * connection is already connected and access to the headers has been lost. See {@link
   * java.net.HttpURLConnection#getRequestProperties()} for details.
   */
public static Request createOkRequest(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) {
    // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
    RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod) ? Util.EMPTY_REQUEST : null;
    Request.Builder builder = new Request.Builder().url(uri.toString()).method(requestMethod, placeholderBody);
    if (requestHeaders != null) {
        Headers headers = extractOkHeaders(requestHeaders, null);
        builder.headers(headers);
    }
    return builder.build();
}
Also used : HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) JavaNetHeaders(okhttp3.internal.JavaNetHeaders) CacheRequest(okhttp3.internal.cache.CacheRequest) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 77 with Headers

use of com.amazonaws.services.s3.Headers in project okhttp by square.

the class JavaApiConverter method createOkResponseForCachePut.

/**
   * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to
   * supply the data. The URLConnection is assumed to already be connected. If this method returns
   * {@code null} the response is uncacheable.
   */
public static Response createOkResponseForCachePut(URI uri, URLConnection urlConnection) throws IOException {
    HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
    Response.Builder okResponseBuilder = new Response.Builder();
    // Request: Create one from the URL connection.
    Headers responseHeaders = createHeaders(urlConnection.getHeaderFields());
    // Some request headers are needed for Vary caching.
    Headers varyHeaders = varyHeaders(urlConnection, responseHeaders);
    if (varyHeaders == null) {
        return null;
    }
    // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
    String requestMethod = httpUrlConnection.getRequestMethod();
    RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod) ? Util.EMPTY_REQUEST : null;
    Request okRequest = new Request.Builder().url(uri.toString()).method(requestMethod, placeholderBody).headers(varyHeaders).build();
    okResponseBuilder.request(okRequest);
    // Status line
    StatusLine statusLine = StatusLine.parse(extractStatusLine(httpUrlConnection));
    okResponseBuilder.protocol(statusLine.protocol);
    okResponseBuilder.code(statusLine.code);
    okResponseBuilder.message(statusLine.message);
    // A network response is required for the Cache to find any Vary headers it needs.
    Response networkResponse = okResponseBuilder.build();
    okResponseBuilder.networkResponse(networkResponse);
    // Response headers
    Headers okHeaders = extractOkResponseHeaders(httpUrlConnection, okResponseBuilder);
    okResponseBuilder.headers(okHeaders);
    // Response body
    ResponseBody okBody = createOkBody(urlConnection);
    okResponseBuilder.body(okBody);
    // Handle SSL handshake information as needed.
    if (httpUrlConnection instanceof HttpsURLConnection) {
        HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) httpUrlConnection;
        Certificate[] peerCertificates;
        try {
            peerCertificates = httpsUrlConnection.getServerCertificates();
        } catch (SSLPeerUnverifiedException e) {
            peerCertificates = null;
        }
        Certificate[] localCertificates = httpsUrlConnection.getLocalCertificates();
        String cipherSuiteString = httpsUrlConnection.getCipherSuite();
        CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
        Handshake handshake = Handshake.get(null, cipherSuite, nullSafeImmutableList(peerCertificates), nullSafeImmutableList(localCertificates));
        okResponseBuilder.handshake(handshake);
    }
    return okResponseBuilder.build();
}
Also used : HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) JavaNetHeaders(okhttp3.internal.JavaNetHeaders) CipherSuite(okhttp3.CipherSuite) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CacheRequest(okhttp3.internal.cache.CacheRequest) Request(okhttp3.Request) ResponseBody(okhttp3.ResponseBody) CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) StatusLine(okhttp3.internal.http.StatusLine) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) RequestBody(okhttp3.RequestBody) Certificate(java.security.cert.Certificate) Handshake(okhttp3.Handshake)

Example 78 with Headers

use of com.amazonaws.services.s3.Headers in project okhttp by square.

the class MockWebServer method writeHttpResponse.

private void writeHttpResponse(Socket socket, BufferedSink sink, MockResponse response) throws IOException {
    sink.writeUtf8(response.getStatus());
    sink.writeUtf8("\r\n");
    Headers headers = response.getHeaders();
    for (int i = 0, size = headers.size(); i < size; i++) {
        sink.writeUtf8(headers.name(i));
        sink.writeUtf8(": ");
        sink.writeUtf8(headers.value(i));
        sink.writeUtf8("\r\n");
    }
    sink.writeUtf8("\r\n");
    sink.flush();
    Buffer body = response.getBody();
    if (body == null)
        return;
    sleepIfDelayed(response);
    throttledTransfer(response, socket, body, sink, body.size(), false);
}
Also used : Buffer(okio.Buffer) Headers(okhttp3.Headers)

Example 79 with Headers

use of com.amazonaws.services.s3.Headers in project okhttp by square.

the class MockWebServer method readRequest.

/** @param sequenceNumber the index of this request on this connection. */
private RecordedRequest readRequest(Socket socket, BufferedSource source, BufferedSink sink, int sequenceNumber) throws IOException {
    String request;
    try {
        request = source.readUtf8LineStrict();
    } catch (IOException streamIsClosed) {
        // no request because we closed the stream
        return null;
    }
    if (request.length() == 0) {
        // no request because the stream is exhausted
        return null;
    }
    Headers.Builder headers = new Headers.Builder();
    long contentLength = -1;
    boolean chunked = false;
    boolean readBody = true;
    String header;
    while ((header = source.readUtf8LineStrict()).length() != 0) {
        Internal.instance.addLenient(headers, header);
        String lowercaseHeader = header.toLowerCase(Locale.US);
        if (contentLength == -1 && lowercaseHeader.startsWith("content-length:")) {
            contentLength = Long.parseLong(header.substring(15).trim());
        }
        if (lowercaseHeader.startsWith("transfer-encoding:") && lowercaseHeader.substring(18).trim().equals("chunked")) {
            chunked = true;
        }
        if (lowercaseHeader.startsWith("expect:") && lowercaseHeader.substring(7).trim().equalsIgnoreCase("100-continue")) {
            readBody = false;
        }
    }
    if (!readBody && dispatcher.peek().getSocketPolicy() == EXPECT_CONTINUE) {
        sink.writeUtf8("HTTP/1.1 100 Continue\r\n");
        sink.writeUtf8("Content-Length: 0\r\n");
        sink.writeUtf8("\r\n");
        sink.flush();
        readBody = true;
    }
    boolean hasBody = false;
    TruncatingBuffer requestBody = new TruncatingBuffer(bodyLimit);
    List<Integer> chunkSizes = new ArrayList<>();
    MockResponse policy = dispatcher.peek();
    if (!readBody) {
    // Don't read the body unless we've invited the client to send it.
    } else if (contentLength != -1) {
        hasBody = contentLength > 0;
        throttledTransfer(policy, socket, source, Okio.buffer(requestBody), contentLength, true);
    } else if (chunked) {
        hasBody = true;
        while (true) {
            int chunkSize = Integer.parseInt(source.readUtf8LineStrict().trim(), 16);
            if (chunkSize == 0) {
                readEmptyLine(source);
                break;
            }
            chunkSizes.add(chunkSize);
            throttledTransfer(policy, socket, source, Okio.buffer(requestBody), chunkSize, true);
            readEmptyLine(source);
        }
    }
    String method = request.substring(0, request.indexOf(' '));
    if (hasBody && !HttpMethod.permitsRequestBody(method)) {
        throw new IllegalArgumentException("Request must not have a body: " + request);
    }
    return new RecordedRequest(request, headers.build(), chunkSizes, requestBody.receivedByteCount, requestBody.buffer, sequenceNumber, socket);
}
Also used : Headers(okhttp3.Headers) ArrayList(java.util.ArrayList) ByteString(okio.ByteString) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 80 with Headers

use of com.amazonaws.services.s3.Headers in project okhttp by square.

the class JavaApiConverterTest method extractOkHeaders.

@Test
public void extractOkHeaders() {
    Map<String, List<String>> javaResponseHeaders = new LinkedHashMap<>();
    javaResponseHeaders.put(null, Arrays.asList("StatusLine"));
    javaResponseHeaders.put("key1", Arrays.asList("value1_1", "value1_2"));
    javaResponseHeaders.put("key2", Arrays.asList("value2"));
    Headers okHeaders = JavaApiConverter.extractOkHeaders(javaResponseHeaders, null);
    // null entry should be stripped out
    assertEquals(3, okHeaders.size());
    assertEquals(Arrays.asList("value1_1", "value1_2"), okHeaders.values("key1"));
    assertEquals(Arrays.asList("value2"), okHeaders.values("key2"));
}
Also used : Headers(okhttp3.Headers) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Aggregations

Headers (okhttp3.Headers)128 Request (okhttp3.Request)61 Response (okhttp3.Response)54 Test (org.junit.Test)40 IOException (java.io.IOException)32 Call (okhttp3.Call)30 RequestBody (okhttp3.RequestBody)25 CancelledException (com.hippo.ehviewer.client.exception.CancelledException)20 EhException (com.hippo.ehviewer.client.exception.EhException)20 NoHAtHClientException (com.hippo.ehviewer.client.exception.NoHAtHClientException)20 ParseException (com.hippo.ehviewer.client.exception.ParseException)20 StatusCodeException (com.hippo.network.StatusCodeException)20 ResponseBody (okhttp3.ResponseBody)18 HttpHeaders (okhttp3.internal.http.HttpHeaders)18 MediaType (okhttp3.MediaType)15 ServiceResponseWithHeaders (com.microsoft.rest.ServiceResponseWithHeaders)14 HeaderResponseBoolHeaders (fixtures.header.models.HeaderResponseBoolHeaders)14 HeaderResponseByteHeaders (fixtures.header.models.HeaderResponseByteHeaders)14 HeaderResponseDateHeaders (fixtures.header.models.HeaderResponseDateHeaders)14 HeaderResponseDatetimeHeaders (fixtures.header.models.HeaderResponseDatetimeHeaders)14