Search in sources :

Example 26 with Header

use of okhttp3.internal.http2.Header in project okhttp by square.

the class InterceptorTest method networkInterceptorsCanChangeRequestMethodFromGetToPost.

@Test
public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
    server.enqueue(new MockResponse());
    Interceptor interceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "abc");
            return chain.proceed(originalRequest.newBuilder().method("POST", body).header("Content-Type", mediaType.toString()).header("Content-Length", Long.toString(body.contentLength())).build());
        }
    };
    client = client.newBuilder().addNetworkInterceptor(interceptor).build();
    Request request = new Request.Builder().url(server.url("/")).get().build();
    client.newCall(request).execute();
    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("POST", recordedRequest.getMethod());
    assertEquals("abc", recordedRequest.getBody().readUtf8());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 27 with Header

use of okhttp3.internal.http2.Header in project okhttp by square.

the class InterceptorTest method rewriteRequestToServer.

private void rewriteRequestToServer(boolean network) throws Exception {
    server.enqueue(new MockResponse());
    addInterceptor(network, new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body())).addHeader("OkHttp-Intercepted", "yep").build());
        }
    });
    Request request = new Request.Builder().url(server.url("/")).addHeader("Original-Header", "foo").method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build();
    client.newCall(request).execute();
    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("ABC", recordedRequest.getBody().readUtf8());
    assertEquals("foo", recordedRequest.getHeader("Original-Header"));
    assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted"));
    assertEquals("POST", recordedRequest.getMethod());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) IOException(java.io.IOException)

Example 28 with Header

use of okhttp3.internal.http2.Header in project okhttp by square.

the class HeadersTest method readNameValueBlockDropsForbiddenHeadersHttp2.

@Test
public void readNameValueBlockDropsForbiddenHeadersHttp2() throws IOException {
    List<Header> headerBlock = headerEntries(":status", "200 OK", ":version", "HTTP/1.1", "connection", "close");
    Request request = new Request.Builder().url("http://square.com/").build();
    Response response = Http2Codec.readHttp2HeadersList(headerBlock).request(request).build();
    Headers headers = response.headers();
    assertEquals(1, headers.size());
    assertEquals(":version", headers.name(0));
    assertEquals("HTTP/1.1", headers.value(0));
}
Also used : Header(okhttp3.internal.http2.Header) HttpHeaders(okhttp3.internal.http.HttpHeaders) Test(org.junit.Test)

Example 29 with Header

use of okhttp3.internal.http2.Header in project okhttp by square.

the class BridgeInterceptor method cookieHeader.

/** Returns a 'Cookie' HTTP request header with all cookies, like {@code a=b; c=d}. */
private String cookieHeader(List<Cookie> cookies) {
    StringBuilder cookieHeader = new StringBuilder();
    for (int i = 0, size = cookies.size(); i < size; i++) {
        if (i > 0) {
            cookieHeader.append("; ");
        }
        Cookie cookie = cookies.get(i);
        cookieHeader.append(cookie.name()).append('=').append(cookie.value());
    }
    return cookieHeader.toString();
}
Also used : Cookie(okhttp3.Cookie)

Example 30 with Header

use of okhttp3.internal.http2.Header in project okhttp by square.

the class CallServerInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    HttpCodec httpCodec = ((RealInterceptorChain) chain).httpStream();
    StreamAllocation streamAllocation = ((RealInterceptorChain) chain).streamAllocation();
    Request request = chain.request();
    long sentRequestMillis = System.currentTimeMillis();
    httpCodec.writeRequestHeaders(request);
    Response.Builder responseBuilder = null;
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
        // we did get (such as a 4xx response) without ever transmitting the request body.
        if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
            httpCodec.flushRequest();
            responseBuilder = httpCodec.readResponseHeaders(true);
        }
        // Write the request body, unless an "Expect: 100-continue" expectation failed.
        if (responseBuilder == null) {
            Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
            BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
            request.body().writeTo(bufferedRequestBody);
            bufferedRequestBody.close();
        }
    }
    httpCodec.finishRequest();
    if (responseBuilder == null) {
        responseBuilder = httpCodec.readResponseHeaders(false);
    }
    Response response = responseBuilder.request(request).handshake(streamAllocation.connection().handshake()).sentRequestAtMillis(sentRequestMillis).receivedResponseAtMillis(System.currentTimeMillis()).build();
    int code = response.code();
    if (forWebSocket && code == 101) {
        // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
        response = response.newBuilder().body(Util.EMPTY_RESPONSE).build();
    } else {
        response = response.newBuilder().body(httpCodec.openResponseBody(response)).build();
    }
    if ("close".equalsIgnoreCase(response.request().header("Connection")) || "close".equalsIgnoreCase(response.header("Connection"))) {
        streamAllocation.noNewStreams();
    }
    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
        throw new ProtocolException("HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }
    return response;
}
Also used : StreamAllocation(okhttp3.internal.connection.StreamAllocation) Response(okhttp3.Response) ProtocolException(java.net.ProtocolException) BufferedSink(okio.BufferedSink) Sink(okio.Sink) Request(okhttp3.Request) BufferedSink(okio.BufferedSink)

Aggregations

Test (org.junit.Test)88 MockResponse (okhttp3.mockwebserver.MockResponse)82 Request (okhttp3.Request)70 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)56 Response (okhttp3.Response)52 IOException (java.io.IOException)50 RequestBody (okhttp3.RequestBody)24 Call (okhttp3.Call)20 OkHttpClient (okhttp3.OkHttpClient)20 Callback (okhttp3.Callback)19 Interceptor (okhttp3.Interceptor)12 FormBody (okhttp3.FormBody)11 ResponseBody (okhttp3.ResponseBody)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)10 Headers (okhttp3.Headers)10 List (java.util.List)9 JSONObject (org.json.JSONObject)7 File (java.io.File)6 HashMap (java.util.HashMap)6