Search in sources :

Example 21 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)

Example 22 with Header

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

the class RealWebSocket method connect.

public void connect(OkHttpClient client) {
    client = client.newBuilder().protocols(ONLY_HTTP1).build();
    final int pingIntervalMillis = client.pingIntervalMillis();
    final Request request = originalRequest.newBuilder().header("Upgrade", "websocket").header("Connection", "Upgrade").header("Sec-WebSocket-Key", key).header("Sec-WebSocket-Version", "13").build();
    call = Internal.instance.newWebSocketCall(client, request);
    call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            try {
                checkResponse(response);
            } catch (ProtocolException e) {
                failWebSocket(e, response);
                closeQuietly(response);
                return;
            }
            // Promote the HTTP streams into web socket streams.
            StreamAllocation streamAllocation = Internal.instance.streamAllocation(call);
            // Prevent connection pooling!
            streamAllocation.noNewStreams();
            Streams streams = streamAllocation.connection().newWebSocketStreams(streamAllocation);
            // Process all web socket messages.
            try {
                listener.onOpen(RealWebSocket.this, response);
                String name = "OkHttp WebSocket " + request.url().redact();
                initReaderAndWriter(name, pingIntervalMillis, streams);
                streamAllocation.connection().socket().setSoTimeout(0);
                loopReader();
            } catch (Exception e) {
                failWebSocket(e, null);
            }
        }

        @Override
        public void onFailure(Call call, IOException e) {
            failWebSocket(e, null);
        }
    });
}
Also used : Response(okhttp3.Response) StreamAllocation(okhttp3.internal.connection.StreamAllocation) Call(okhttp3.Call) ProtocolException(java.net.ProtocolException) Callback(okhttp3.Callback) Request(okhttp3.Request) ByteString(okio.ByteString) IOException(java.io.IOException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException)

Example 23 with Header

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

the class BridgeInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    RequestBody body = userRequest.body();
    if (body != null) {
        MediaType contentType = body.contentType();
        if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString());
        }
        long contentLength = body.contentLength();
        if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
        } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
        }
    }
    if (userRequest.header("Host") == null) {
        requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") == null) {
        requestBuilder.header("Connection", "Keep-Alive");
    }
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
        transparentGzip = true;
        requestBuilder.header("Accept-Encoding", "gzip");
    }
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
        requestBuilder.header("Cookie", cookieHeader(cookies));
    }
    if (userRequest.header("User-Agent") == null) {
        requestBuilder.header("User-Agent", Version.userAgent());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);
    if (transparentGzip && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding")) && HttpHeaders.hasBody(networkResponse)) {
        GzipSource responseBody = new GzipSource(networkResponse.body().source());
        Headers strippedHeaders = networkResponse.headers().newBuilder().removeAll("Content-Encoding").removeAll("Content-Length").build();
        responseBuilder.headers(strippedHeaders);
        responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }
    return responseBuilder.build();
}
Also used : Cookie(okhttp3.Cookie) Headers(okhttp3.Headers) Request(okhttp3.Request) Response(okhttp3.Response) GzipSource(okio.GzipSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 24 with Header

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

the class AccessHeaders method run.

public void run() throws Exception {
    Request request = new Request.Builder().url("https://api.github.com/repos/square/okhttp/issues").header("User-Agent", "OkHttp Headers.java").addHeader("Accept", "application/json; q=0.5").addHeader("Accept", "application/vnd.github.v3+json").build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        System.out.println("Server: " + response.header("Server"));
        System.out.println("Date: " + response.header("Date"));
        System.out.println("Vary: " + response.headers("Vary"));
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Example 25 with Header

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

the class RequestBuilderTest method headerParam.

@Test
public void headerParam() {
    class Example {

        //
        @GET("/foo/bar/")
        //
        @Headers("ping: pong")
        Call<ResponseBody> method(@Header("kit") String kit) {
            return null;
        }
    }
    Request request = buildRequest(Example.class, "kat");
    assertThat(request.method()).isEqualTo("GET");
    okhttp3.Headers headers = request.headers();
    assertThat(headers.size()).isEqualTo(2);
    assertThat(headers.get("ping")).isEqualTo("pong");
    assertThat(headers.get("kit")).isEqualTo("kat");
    assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
    assertThat(request.body()).isNull();
}
Also used : Header(retrofit2.http.Header) Request(okhttp3.Request) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)89 MockResponse (okhttp3.mockwebserver.MockResponse)82 Request (okhttp3.Request)75 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)56 Response (okhttp3.Response)54 IOException (java.io.IOException)53 RequestBody (okhttp3.RequestBody)24 OkHttpClient (okhttp3.OkHttpClient)22 Call (okhttp3.Call)20 Callback (okhttp3.Callback)19 Interceptor (okhttp3.Interceptor)14 ResponseBody (okhttp3.ResponseBody)12 FormBody (okhttp3.FormBody)11 Headers (okhttp3.Headers)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)10 List (java.util.List)9 JSONObject (org.json.JSONObject)8 File (java.io.File)6 HashMap (java.util.HashMap)6