public static RequestBody create(final MediaType contentType, final byte[] content, final int offset, final int byteCount) { if (content == null) { throw new NullPointerException("content == null"); } Util.checkOffsetAndCount((long) content.length, (long) offset, (long) byteCount); return new RequestBody() { public MediaType contentType() { return contentType; } public long contentLength() { return (long) byteCount; } public void writeTo(BufferedSink sink) throws IOException { sink.write(content, offset, byteCount); } }; }
public static RequestBody create(final MediaType contentType, final File file) { if (file != null) { return new RequestBody() { public MediaType contentType() { return contentType; } public long contentLength() { return file.length(); } public void writeTo(BufferedSink sink) throws IOException { Closeable source = null; try { source = Okio.source(file); sink.writeAll(source); } finally { Util.closeQuietly(source); } } }; } throw new NullPointerException("content == null"); }
Response get(Request request) { try { Closeable snapshot = this.cache.get(urlToKey(request)); if (snapshot == null) { return null; } try { Entry entry = new Entry(snapshot.getSource(0)); Response response = entry.response(request, snapshot); if (entry.matches(request, response)) { return response; } Util.closeQuietly(response.body()); return null; } catch (IOException e) { Util.closeQuietly(snapshot); return null; } } catch (IOException e2) { return null; } }
public void evictAll() { List<RealConnection> evictedConnections = new ArrayList(); synchronized (this) { Iterator<RealConnection> i = this.connections.iterator(); while (i.hasNext()) { RealConnection connection = (RealConnection) i.next(); if (connection.allocations.isEmpty()) { connection.noNewStreams = true; evictedConnections.add(connection); i.remove(); } } } for (RealConnection connection2 : evictedConnections) { Util.closeQuietly(connection2.getSocket()); } }
public boolean equals(Object other) { if (!(other instanceof Address)) { return false; } Address that = (Address) other; if (this.url.equals(that.url) && this.dns.equals(that.dns) && this.authenticator.equals (that.authenticator) && this.protocols.equals(that.protocols) && this .connectionSpecs.equals(that.connectionSpecs) && this.proxySelector.equals(that .proxySelector) && Util.equal(this.proxy, that.proxy) && Util.equal(this .sslSocketFactory, that.sslSocketFactory) && Util.equal(this.hostnameVerifier, that.hostnameVerifier) && Util.equal(this.certificatePinner, that .certificatePinner)) { return true; } return false; }
private FilterInputStream getFromCache(String url) throws Exception { DiskLruCache cache = DiskLruCache.open(CommonUtil.getImageSavePath(), 1, 2, 2*1024*1024); cache.flush(); String key = Util.hash(url); final DiskLruCache.Snapshot snapshot; try { snapshot = cache.get(key); if (snapshot == null) { return null; } } catch (IOException e) { return null; } FilterInputStream bodyIn = new FilterInputStream(snapshot.getInputStream(1)) { @Override public void close() throws IOException { snapshot.close(); super.close(); } }; return bodyIn; }
private Request networkRequest(Request request) throws IOException { Request.Builder result = request.newBuilder(); if (request.header("Host") == null) { result.header("Host", Util.hostHeader(request.httpUrl())); } if (request.header("Connection") == null) { result.header("Connection", "Keep-Alive"); } if (request.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING) == null) { this.transparentGzip = true; result.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING, AsyncHttpClient.ENCODING_GZIP); } CookieHandler cookieHandler = this.client.getCookieHandler(); if (cookieHandler != null) { OkHeaders.addCookies(result, cookieHandler.get(request.uri(), OkHeaders.toMultimap (result.build().headers(), null))); } if (request.header(Network.USER_AGENT) == null) { result.header(Network.USER_AGENT, Version.userAgent()); } return result.build(); }
protected void execute() { ErrorCode connectionErrorCode = ErrorCode.INTERNAL_ERROR; ErrorCode streamErrorCode = ErrorCode.INTERNAL_ERROR; try { if (!FramedConnection.this.client) { this.frameReader.readConnectionPreface(); } while (true) { if (!this.frameReader.nextFrame(this)) { break; } } connectionErrorCode = ErrorCode.NO_ERROR; streamErrorCode = ErrorCode.CANCEL; } catch (IOException e) { connectionErrorCode = ErrorCode.PROTOCOL_ERROR; streamErrorCode = ErrorCode.PROTOCOL_ERROR; } finally { try { FramedConnection.this.close(connectionErrorCode, streamErrorCode); } catch (IOException e2) { } Util.closeQuietly(this.frameReader); } }
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) { String[] cipherSuitesIntersection; String[] tlsVersionsIntersection; if (this.cipherSuites != null) { cipherSuitesIntersection = (String[]) Util.intersect(String.class, this.cipherSuites, sslSocket.getEnabledCipherSuites()); } else { cipherSuitesIntersection = sslSocket.getEnabledCipherSuites(); } if (this.tlsVersions != null) { tlsVersionsIntersection = (String[]) Util.intersect(String.class, this.tlsVersions, sslSocket.getEnabledProtocols()); } else { tlsVersionsIntersection = sslSocket.getEnabledProtocols(); } if (isFallback && Util.contains(sslSocket.getSupportedCipherSuites(), "TLS_FALLBACK_SCSV")) { cipherSuitesIntersection = Util.concat(cipherSuitesIntersection, "TLS_FALLBACK_SCSV"); } return new Builder(this).cipherSuites(cipherSuitesIntersection).tlsVersions (tlsVersionsIntersection).build(); }
public synchronized void cancel(Object tag) { for (AsyncCall call : this.readyCalls) { if (Util.equal(tag, call.tag())) { call.cancel(); } } for (AsyncCall call2 : this.runningCalls) { if (Util.equal(tag, call2.tag())) { call2.get().canceled = true; HttpEngine engine = call2.get().engine; if (engine != null) { engine.cancel(); } } } for (Call call3 : this.executedCalls) { if (Util.equal(tag, call3.tag())) { call3.cancel(); } } }
public static Handshake get(SSLSession session) { String cipherSuite = session.getCipherSuite(); if (cipherSuite == null) { throw new IllegalStateException("cipherSuite == null"); } Certificate[] peerCertificates; List<Certificate> peerCertificatesList; List<Certificate> localCertificatesList; try { peerCertificates = session.getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { peerCertificates = null; } if (peerCertificates != null) { peerCertificatesList = Util.immutableList(peerCertificates); } else { peerCertificatesList = Collections.emptyList(); } Certificate[] localCertificates = session.getLocalCertificates(); if (localCertificates != null) { localCertificatesList = Util.immutableList(localCertificates); } else { localCertificatesList = Collections.emptyList(); } return new Handshake(cipherSuite, peerCertificatesList, localCertificatesList); }
public final byte[] bytes() throws IOException { long contentLength = contentLength(); if (contentLength > Integer.MAX_VALUE) { throw new IOException("Cannot buffer entire body for content length: " + contentLength); } if (contentLength != -1) { byte[] content = new byte[(int) contentLength]; InputStream in = byteStream(); Util.readFully(in, content); if (in.read() != -1) throw new IOException("Content-Length and stream length disagree"); return content; } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); Util.copy(byteStream(), out); return out.toByteArray(); } }
/** * Releases this engine so that its resources may be either reused or * closed. Also call {@link #automaticallyReleaseConnectionToPool} unless * the connection will be used to follow a redirect. */ public final void release(boolean streamCanceled) { // If the response body comes from the cache, close it. if (responseBodyIn == cachedResponseBody) { Util.closeQuietly(responseBodyIn); } if (!connectionReleased && connection != null) { connectionReleased = true; if (transport == null || !transport.makeReusable(streamCanceled, requestBodyOut, responseTransferIn)) { Util.closeQuietly(connection); connection = null; } else if (automaticallyReleaseConnectionToPool) { client.getConnectionPool().recycle(connection); connection = null; } } }
private void readChunkSize() throws IOException { // read the suffix of the previous chunk if (bytesRemainingInChunk != NO_CHUNK_YET) { Util.readAsciiLine(in); } String chunkSizeString = Util.readAsciiLine(in); int index = chunkSizeString.indexOf(";"); if (index != -1) { chunkSizeString = chunkSizeString.substring(0, index); } try { bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16); } catch (NumberFormatException e) { throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString); } if (bytesRemainingInChunk == 0) { hasMoreChunks = false; RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders(); RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders); httpEngine.receiveHeaders(rawResponseHeaders); endOfInput(); } }
/** * Discards the response body so that the connection can be reused. This * needs to be done judiciously, since it delays the current request in * order to speed up a potential future request that may never occur. * * <p>A stream may be discarded to encourage response caching (a response * cannot be cached unless it is consumed completely) or to enable connection * reuse. */ private static boolean discardStream(HttpEngine httpEngine, InputStream responseBodyIn) { Connection connection = httpEngine.connection; if (connection == null) return false; Socket socket = connection.getSocket(); if (socket == null) return false; try { int socketTimeout = socket.getSoTimeout(); socket.setSoTimeout(DISCARD_STREAM_TIMEOUT_MILLIS); try { Util.skipAll(responseBodyIn); return true; } finally { socket.setSoTimeout(socketTimeout); } } catch (IOException e) { return false; } }
@Override public void close() throws IOException { if (!mClosed) { Util.closeQuietly(mFileOutputStream); mByteArrayOutputStream.reset(); mClosed = true; } }
public static RequestBody create(MediaType contentType, String content) { Charset charset = Util.UTF_8; if (contentType != null) { charset = contentType.charset(); if (charset == null) { charset = Util.UTF_8; contentType = MediaType.parse(contentType + "; charset=utf-8"); } } return create(contentType, content.getBytes(charset)); }
public void abort() { synchronized (Cache.this) { if (this.done) { return; } this.done = true; Cache.this.writeAbortCount = Cache.this.writeAbortCount + 1; Util.closeQuietly(this.cacheOut); try { this.editor.abort(); } catch (IOException e) { } } }
public OkHttpClient setProtocols(List<Protocol> protocols) { List protocols2 = Util.immutableList((List) protocols); if (!protocols2.contains(Protocol.HTTP_1_1)) { throw new IllegalArgumentException("protocols doesn't contain http/1.1: " + protocols2); } else if (protocols2.contains(Protocol.HTTP_1_0)) { throw new IllegalArgumentException("protocols must not contain http/1.0: " + protocols2); } else if (protocols2.contains(null)) { throw new IllegalArgumentException("protocols must not contain null"); } else { this.protocols = Util.immutableList(protocols2); return this; } }
public MultipartBuilder$MultipartRequestBody(MediaType type, ByteString boundary, List<Headers> partHeaders, List<RequestBody> partBodies) { if (type == null) { throw new NullPointerException("type == null"); } this.boundary = boundary; this.contentType = MediaType.parse(type + "; boundary=" + boundary.utf8()); this.partHeaders = Util.immutableList(partHeaders); this.partBodies = Util.immutableList(partBodies); }
public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) { this.executor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), Util.threadFactory("OkHttp ConnectionPool", true)); this.cleanupRunnable = new Runnable() { public void run() { while (true) { long waitNanos = ConnectionPool.this.cleanup(System.nanoTime()); if (waitNanos != -1) { if (waitNanos > 0) { long waitMillis = waitNanos / 1000000; waitNanos -= waitMillis * 1000000; synchronized (ConnectionPool.this) { try { ConnectionPool.this.wait(waitMillis, (int) waitNanos); } catch (InterruptedException e) { } } } } else { return; } } } }; this.connections = new ArrayDeque(); this.routeDatabase = new RouteDatabase(); this.maxIdleConnections = maxIdleConnections; this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration); if (keepAliveDuration <= 0) { throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration); } }
long cleanup(long now) { int inUseConnectionCount = 0; int idleConnectionCount = 0; RealConnection longestIdleConnection = null; long longestIdleDurationNs = Long.MIN_VALUE; synchronized (this) { for (RealConnection connection : this.connections) { if (pruneAndGetAllocationCount(connection, now) > 0) { inUseConnectionCount++; } else { idleConnectionCount++; long idleDurationNs = now - connection.idleAtNanos; if (idleDurationNs > longestIdleDurationNs) { longestIdleDurationNs = idleDurationNs; longestIdleConnection = connection; } } } if (longestIdleDurationNs >= this.keepAliveDurationNs || idleConnectionCount > this .maxIdleConnections) { this.connections.remove(longestIdleConnection); Util.closeQuietly(longestIdleConnection.getSocket()); return 0; } else if (idleConnectionCount > 0) { r10 = this.keepAliveDurationNs - longestIdleDurationNs; return r10; } else if (inUseConnectionCount > 0) { r10 = this.keepAliveDurationNs; return r10; } else { return -1; } } }
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory, SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier, CertificatePinner certificatePinner, Authenticator authenticator, Proxy proxy, List<Protocol> protocols, List<ConnectionSpec> connectionSpecs, ProxySelector proxySelector) { this.url = new Builder().scheme(sslSocketFactory != null ? b.a : "http").host(uriHost) .port(uriPort).build(); if (dns == null) { throw new IllegalArgumentException("dns == null"); } this.dns = dns; if (socketFactory == null) { throw new IllegalArgumentException("socketFactory == null"); } this.socketFactory = socketFactory; if (authenticator == null) { throw new IllegalArgumentException("authenticator == null"); } this.authenticator = authenticator; if (protocols == null) { throw new IllegalArgumentException("protocols == null"); } this.protocols = Util.immutableList((List) protocols); if (connectionSpecs == null) { throw new IllegalArgumentException("connectionSpecs == null"); } this.connectionSpecs = Util.immutableList((List) connectionSpecs); if (proxySelector == null) { throw new IllegalArgumentException("proxySelector == null"); } this.proxySelector = proxySelector; this.proxy = proxy; this.sslSocketFactory = sslSocketFactory; this.hostnameVerifier = hostnameVerifier; this.certificatePinner = certificatePinner; }
public static ResponseBody create(MediaType contentType, String content) { Charset charset = Util.UTF_8; if (contentType != null) { charset = contentType.charset(); if (charset == null) { charset = Util.UTF_8; contentType = MediaType.parse(contentType + "; charset=utf-8"); } } Buffer buffer = new Buffer().writeString(content, charset); return create(contentType, buffer.size(), buffer); }
public void close() throws IOException { if (!this.closed) { if (this.hasMoreChunks && !Util.discard(this, 100, TimeUnit.MILLISECONDS)) { unexpectedEndOfInput(); } this.closed = true; } }
public void write(Buffer source, long byteCount) throws IOException { if (this.closed) { throw new IllegalStateException("closed"); } Util.checkOffsetAndCount(source.size(), 0, byteCount); if (byteCount > this.bytesRemaining) { throw new ProtocolException("expected " + this.bytesRemaining + " bytes but " + "received " + byteCount); } Http1xStream.this.sink.write(source, byteCount); this.bytesRemaining -= byteCount; }
public void close() throws IOException { if (!this.closed) { if (!(this.bytesRemaining == 0 || Util.discard(this, 100, TimeUnit.MILLISECONDS))) { unexpectedEndOfInput(); } this.closed = true; } }
public void write(Buffer source, long byteCount) throws IOException { if (this.closed) { throw new IllegalStateException("closed"); } Util.checkOffsetAndCount(source.size(), 0, byteCount); if (this.limit == -1 || this.content.size() <= ((long) this.limit) - byteCount) { this.content.write(source, byteCount); return; } throw new ProtocolException("exceeded content-length limit of " + this.limit + " bytes"); }
public static boolean varyMatches(Response cachedResponse, Headers cachedRequest, Request newRequest) { for (String field : varyFields(cachedResponse)) { if (!Util.equal(cachedRequest.values(field), newRequest.headers(field))) { return false; } } return true; }
public StreamAllocation close() { if (this.bufferedRequestBody != null) { Util.closeQuietly(this.bufferedRequestBody); } else if (this.requestBodyOut != null) { Util.closeQuietly(this.requestBodyOut); } if (this.userResponse != null) { Util.closeQuietly(this.userResponse.body()); } else { this.streamAllocation.connectionFailed(); } return this.streamAllocation; }
public void close() throws IOException { if (!(this.cacheRequestClosed || Util.discard(this, 100, TimeUnit.MILLISECONDS))) { this.cacheRequestClosed = true; this.val$cacheRequest.abort(); } this.val$source.close(); }
private void deallocate(boolean noNewStreams, boolean released, boolean streamFinished) { RealConnection connectionToClose = null; synchronized (this.connectionPool) { if (streamFinished) { this.stream = null; } if (released) { this.released = true; } if (this.connection != null) { if (noNewStreams) { this.connection.noNewStreams = true; } if (this.stream == null && (this.released || this.connection.noNewStreams)) { release(this.connection); if (this.connection.streamCount > 0) { this.routeSelector = null; } if (this.connection.allocations.isEmpty()) { this.connection.idleAtNanos = System.nanoTime(); if (Internal.instance.connectionBecameIdle(this.connectionPool, this .connection)) { connectionToClose = this.connection; } } this.connection = null; } } } if (connectionToClose != null) { Util.closeQuietly(connectionToClose.getSocket()); } }
public void shutdown(ErrorCode statusCode) throws IOException { synchronized (this.frameWriter) { synchronized (this) { if (this.shutdown) { return; } this.shutdown = true; int lastGoodStreamId = this.lastGoodStreamId; this.frameWriter.goAway(lastGoodStreamId, statusCode, Util.EMPTY_BYTE_ARRAY); } } }
private void createTunnel(int readTimeout, int writeTimeout) throws IOException { Request tunnelRequest = createTunnelRequest(); HttpUrl url = tunnelRequest.httpUrl(); String requestLine = "CONNECT " + url.host() + ":" + url.port() + " HTTP/1.1"; do { Http1xStream tunnelConnection = new Http1xStream(null, this.source, this.sink); this.source.timeout().timeout((long) readTimeout, TimeUnit.MILLISECONDS); this.sink.timeout().timeout((long) writeTimeout, TimeUnit.MILLISECONDS); tunnelConnection.writeRequest(tunnelRequest.headers(), requestLine); tunnelConnection.finishRequest(); Response response = tunnelConnection.readResponse().request(tunnelRequest).build(); long contentLength = OkHeaders.contentLength(response); if (contentLength == -1) { contentLength = 0; } Source body = tunnelConnection.newFixedLengthSource(contentLength); Util.skipAll(body, ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED, TimeUnit .MILLISECONDS); body.close(); switch (response.code()) { case 200: if (!this.source.buffer().exhausted() || !this.sink.buffer().exhausted()) { throw new IOException("TLS tunnel buffered too many bytes!"); } return; case 407: tunnelRequest = OkHeaders.processAuthHeader(this.route.getAddress() .getAuthenticator(), response, this.route.getProxy()); break; default: throw new IOException("Unexpected response code for CONNECT: " + response .code()); } } while (tunnelRequest != null); throw new IOException("Failed to authenticate with proxy"); }
public List<CipherSuite> cipherSuites() { if (this.cipherSuites == null) { return null; } Object[] result = new CipherSuite[this.cipherSuites.length]; for (int i = 0; i < this.cipherSuites.length; i++) { result[i] = CipherSuite.forJavaName(this.cipherSuites[i]); } return Util.immutableList(result); }
@Override public void data(boolean inFinished, int streamId, InputStream in, int length) throws IOException { SpdyStream dataStream = getStream(streamId); if (dataStream == null) { writeSynResetLater(streamId, ErrorCode.INVALID_STREAM); Util.skipByReading(in, length); return; } dataStream.receiveData(in, length); if (inFinished) { dataStream.receiveFin(); } }
private static boolean nonEmptyIntersection(String[] a, String[] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { return false; } for (String toFind : a) { if (Util.contains(b, toFind)) { return true; } } return false; }