Search in sources :

Example 31 with Connection

use of okhttp3.Connection 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 32 with Connection

use of okhttp3.Connection in project okhttp by square.

the class RealConnection method connectSocket.

/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout) throws IOException {
    Proxy proxy = route.proxy();
    Address address = route.address();
    rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP ? address.socketFactory().createSocket() : new Socket(proxy);
    rawSocket.setSoTimeout(readTimeout);
    try {
        Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
    } catch (ConnectException e) {
        ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
        ce.initCause(e);
        throw ce;
    }
    source = Okio.buffer(Okio.source(rawSocket));
    sink = Okio.buffer(Okio.sink(rawSocket));
}
Also used : Proxy(java.net.Proxy) Address(okhttp3.Address) SSLSocket(javax.net.ssl.SSLSocket) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 33 with Connection

use of okhttp3.Connection in project okhttp by square.

the class StreamAllocation method findConnection.

/**
   * Returns a connection to host a new stream. This prefers the existing connection if it exists,
   * then the pool, finally building a new connection.
   */
private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) throws IOException {
    Route selectedRoute;
    synchronized (connectionPool) {
        if (released)
            throw new IllegalStateException("released");
        if (codec != null)
            throw new IllegalStateException("codec != null");
        if (canceled)
            throw new IOException("Canceled");
        // Attempt to use an already-allocated connection.
        RealConnection allocatedConnection = this.connection;
        if (allocatedConnection != null && !allocatedConnection.noNewStreams) {
            return allocatedConnection;
        }
        // Attempt to get a connection from the pool.
        Internal.instance.get(connectionPool, address, this, null);
        if (connection != null) {
            return connection;
        }
        selectedRoute = route;
    }
    // If we need a route, make one. This is a blocking operation.
    if (selectedRoute == null) {
        selectedRoute = routeSelector.next();
    }
    RealConnection result;
    synchronized (connectionPool) {
        if (canceled)
            throw new IOException("Canceled");
        // Now that we have an IP address, make another attempt at getting a connection from the pool.
        // This could match due to connection coalescing.
        Internal.instance.get(connectionPool, address, this, selectedRoute);
        if (connection != null)
            return connection;
        // Create a connection and assign it to this allocation immediately. This makes it possible
        // for an asynchronous cancel() to interrupt the handshake we're about to do.
        route = selectedRoute;
        refusedStreamCount = 0;
        result = new RealConnection(connectionPool, selectedRoute);
        acquire(result);
    }
    // Do TCP + TLS handshakes. This is a blocking operation.
    result.connect(connectTimeout, readTimeout, writeTimeout, connectionRetryEnabled);
    routeDatabase().connected(result.route());
    Socket socket = null;
    synchronized (connectionPool) {
        // Pool the connection.
        Internal.instance.put(connectionPool, result);
        // release this connection and acquire that one.
        if (result.isMultiplexed()) {
            socket = Internal.instance.deduplicate(connectionPool, address, this);
            result = connection;
        }
    }
    closeQuietly(socket);
    return result;
}
Also used : IOException(java.io.IOException) Route(okhttp3.Route) Socket(java.net.Socket)

Example 34 with Connection

use of okhttp3.Connection 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 35 with Connection

use of okhttp3.Connection in project okhttp by square.

the class ConnectInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();
    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
Also used : HttpCodec(okhttp3.internal.http.HttpCodec) RealInterceptorChain(okhttp3.internal.http.RealInterceptorChain) Request(okhttp3.Request)

Aggregations

Test (org.junit.Test)226 MockResponse (okhttp3.mockwebserver.MockResponse)215 HttpURLConnection (java.net.HttpURLConnection)106 IOException (java.io.IOException)79 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)67 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)59 URLConnection (java.net.URLConnection)53 Response (okhttp3.Response)43 Connection (com.trilead.ssh2.Connection)40 InputStream (java.io.InputStream)40 Request (okhttp3.Request)38 OkHttpURLConnection (okhttp3.internal.huc.OkHttpURLConnection)36 URL (java.net.URL)32 Session (com.trilead.ssh2.Session)31 InFrame (okhttp3.internal.http2.MockHttp2Peer.InFrame)28 Buffer (okio.Buffer)26 OutputStream (java.io.OutputStream)19 InterruptedIOException (java.io.InterruptedIOException)15 Call (okhttp3.Call)14 ResponseBody (okhttp3.ResponseBody)14