private CacheRequest put(Response response) throws IOException { String requestMethod = response.request().method(); if (HttpMethod.invalidatesCache(response.request().method())) { try { remove(response.request()); return null; } catch (IOException e) { return null; } } else if (!requestMethod.equals("GET") || OkHeaders.hasVaryAll(response)) { return null; } else { Entry entry = new Entry(response); try { Editor editor = this.cache.edit(urlToKey(response.request())); if (editor == null) { return null; } entry.writeTo(editor); return new CacheRequestImpl(editor); } catch (IOException e2) { abortQuietly(null); return null; } } }
/** * Creates an OkHttp Response.Body containing the supplied information. */ private static ResponseBody createOkBody(final Headers okHeaders, InputStream body) { final BufferedSource source = Okio.buffer(Okio.source(body)); return new ResponseBody() { @Override public MediaType contentType() { String contentTypeHeader = okHeaders.get("Content-Type"); return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader); } @Override public long contentLength() { return OkHeaders.contentLength(okHeaders); } @Override public BufferedSource source() { return source; } }; }
public Entry(Response response) { this.url = response.request().urlString(); this.varyHeaders = OkHeaders.varyHeaders(response); this.requestMethod = response.request().method(); this.protocol = response.protocol(); this.code = response.code(); this.message = response.message(); this.responseHeaders = response.headers(); this.handshake = response.handshake(); }
public List<Challenge> challenges() { String responseField; if (this.code == SampleTinkerReport.KEY_LOADED_SUCC_COST_1000_LESS) { responseField = "WWW-Authenticate"; } else if (this.code != 407) { return Collections.emptyList(); } else { responseField = "Proxy-Authenticate"; } return OkHeaders.parseChallenges(headers(), responseField); }
private Headers getHeaders() throws IOException { if (this.responseHeaders == null) { Response response = getResponse().getResponse(); this.responseHeaders = response.headers().newBuilder().add(OkHeaders .SELECTED_PROTOCOL, response.protocol().toString()).add(OkHeaders .RESPONSE_SOURCE, responseSourceHeader(response)).build(); } return this.responseHeaders; }
public final Map<String, List<String>> getHeaderFields() { try { return OkHeaders.toMultimap(getHeaders(), StatusLine.get(getResponse().getResponse()) .toString()); } catch (IOException e) { return Collections.emptyMap(); } }
public final Map<String, List<String>> getRequestProperties() { if (!this.connected) { return OkHeaders.toMultimap(this.requestHeaders.build(), null); } throw new IllegalStateException("Cannot access request header fields after connection is " + "set"); }
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"); }
@Override public void onResponse(Response response) throws IOException { if(response.isSuccessful()) { try { long startTime = SystemClock.elapsedRealtime(); byte[] segmentData = response.body().bytes(); /* The time it takes to send the request header to the server until the response * headers arrive. Can be custom implemented through an Interceptor too, in case * this should ever fail in the future. */ long headerTime = Long.parseLong(response.header(OkHeaders.RECEIVED_MILLIS)) - Long.parseLong(response.header(OkHeaders.SENT_MILLIS)); /* The time it takes to read the result body, which is the actual segment data. * The sum of this time together with the header time is the total segment download time. */ long payloadTime = SystemClock.elapsedRealtime() - startTime; mAdaptationLogic.reportSegmentDownload(mAdaptationSet, mCachedSegment.representation, mCachedSegment.segment, segmentData.length, headerTime + payloadTime); handleSegment(segmentData, mCachedSegment); mFutureCacheRequests.remove(mCachedSegment.number); mFutureCache.put(mCachedSegment.number, mCachedSegment); Log.d(TAG, "async cached " + mCachedSegment.number + " " + mCachedSegment.segment.toString() + " -> " + mCachedSegment.file.getPath()); synchronized (mFutureCache) { mFutureCache.notify(); } } catch(Exception e) { Log.e(TAG, "onResponse", e); } finally { response.body().close(); } } }
final void makeTunnel(Request paramRequest, int paramInt1, int paramInt2) throws IOException { HttpConnection localHttpConnection = new HttpConnection(this.pool, this, this.socket); localHttpConnection.setTimeouts(paramInt1, paramInt2); URL localURL = paramRequest.url(); String str = "CONNECT " + localURL.getHost() + ":" + localURL.getPort() + " HTTP/1.1"; do { localHttpConnection.writeRequest(paramRequest.headers, str); localHttpConnection.flush(); Response.Builder localBuilder = localHttpConnection.readResponse(); localBuilder.request = paramRequest; Response localResponse = localBuilder.build(); long l = OkHeaders.contentLength(localResponse); if (l == -1L) { l = 0L; } Source localSource = localHttpConnection.newFixedLengthSource(l); Util.skipAll(localSource, 2147483647, TimeUnit.MILLISECONDS); localSource.close(); switch (localResponse.code) { default: throw new IOException("Unexpected response code for CONNECT: " + localResponse.code); case 200: if (localHttpConnection.source.buffer().size <= 0L) { break; } throw new IOException("TLS tunnel buffered too many bytes!"); case 407: paramRequest = OkHeaders.processAuthHeader(this.route.address.authenticator, localResponse, this.route.proxy); } } while (paramRequest != null); throw new IOException("Failed to authenticate with proxy"); }
public final List<Challenge> challenges() { if (this.code == 401) {} for (String str = "WWW-Authenticate";; str = "Proxy-Authenticate") { return OkHeaders.parseChallenges(this.headers, str); if (this.code != 407) { break; } } return Collections.emptyList(); }
/** * To make an HTTPS connection over an HTTP proxy, send an unencrypted * CONNECT request to create the proxy connection. This may need to be * retried if the proxy requires authorization. */ private void makeTunnel(Request request, int readTimeout, int writeTimeout) throws IOException { HttpConnection tunnelConnection = new HttpConnection(pool, this, socket); tunnelConnection.setTimeouts(readTimeout, writeTimeout); URL url = request.url(); String requestLine = "CONNECT " + url.getHost() + ":" + url.getPort() + " HTTP/1.1"; while (true) { tunnelConnection.writeRequest(request.headers(), requestLine); tunnelConnection.flush(); Response response = tunnelConnection.readResponse().request(request).build(); tunnelConnection.emptyResponseBody(); switch (response.code()) { case HTTP_OK: // Assume the server won't send a TLS ServerHello until we send a TLS ClientHello. If that // happens, then we will have buffered bytes that are needed by the SSLSocket! if (tunnelConnection.bufferSize() > 0) { throw new IOException("TLS tunnel buffered too many bytes!"); } return; case HTTP_PROXY_AUTH: request = OkHeaders.processAuthHeader( route.address.authenticator, response, route.proxy); if (request != null) continue; throw new IOException("Failed to authenticate with proxy"); default: throw new IOException( "Unexpected response code for CONNECT: " + response.code()); } } }
private CacheRequest put(Response response) throws IOException { String requestMethod = response.request().method(); if (HttpMethod.invalidatesCache(response.request().method())) { try { remove(response.request()); } catch (IOException ignored) { // The cache cannot be written. } return null; } if (!requestMethod.equals("GET")) { // Don't cache non-GET responses. We're technically allowed to cache // HEAD requests and some POST requests, but the complexity of doing // so is high and the benefit is low. return null; } if (OkHeaders.hasVaryAll(response)) { return null; } Entry entry = new Entry(response); DiskLruCache.Editor editor = null; try { editor = cache.edit(urlToKey(response.request())); if (editor == null) { return null; } entry.writeTo(editor); return new CacheRequestImpl(editor); } catch (IOException e) { abortQuietly(editor); return null; } }
/** * Returns the authorization challenges appropriate for this response's code. * If the response code is 401 unauthorized, this returns the * "WWW-Authenticate" challenges. If the response code is 407 proxy * unauthorized, this returns the "Proxy-Authenticate" challenges. Otherwise * this returns an empty list of challenges. */ public List<Challenge> challenges() { String responseField; if (code == HTTP_UNAUTHORIZED) { responseField = "WWW-Authenticate"; } else if (code == HTTP_PROXY_AUTH) { responseField = "Proxy-Authenticate"; } else { return Collections.emptyList(); } return OkHeaders.parseChallenges(headers(), responseField); }
@Override public final Map<String, List<String>> getHeaderFields() { try { return OkHeaders.toMultimap(getHeaders(), StatusLine.get(getResponse().getResponse()).toString()); } catch (IOException e) { return Collections.emptyMap(); } }
@Override public final Map<String, List<String>> getRequestProperties() { if (connected) { throw new IllegalStateException( "Cannot access request header fields after connection is set"); } return OkHeaders.toMultimap(requestHeaders.build(), null); }
public void fetch(URL url) throws IOException { HttpURLConnection connection = client.open(url); String responseSource = connection.getHeaderField(OkHeaders.RESPONSE_SOURCE); String contentType = connection.getHeaderField("Content-Type"); int responseCode = connection.getResponseCode(); System.out.printf("%03d: %s %s%n", responseCode, url, responseSource); if (responseCode >= 400) { connection.getErrorStream().close(); return; } InputStream in = connection.getInputStream(); if (responseCode != 200 || contentType == null) { in.close(); return; } MediaType mediaType = MediaType.parse(contentType); Document document = Jsoup.parse(in, mediaType.charset(UTF_8).name(), url.toString()); for (Element element : document.select("a[href]")) { String href = element.attr("href"); URL link = parseUrl(url, href); if (link != null) queue.add(link); } in.close(); }
public boolean matches(Request request, Response response) { return this.url.equals(request.urlString()) && this.requestMethod.equals(request .method()) && OkHeaders.varyMatches(response, this.varyHeaders, request); }
public boolean matches(Request request, Response response) { return url.equals(request.urlString()) && requestMethod.equals(request.method()) && OkHeaders.varyMatches(response, varyHeaders, request); }
@Override public long contentLength() { return OkHeaders.contentLength(response); }
/** * Extracts an immutable request header map from the supplied {@link com.squareup.okhttp.Headers}. */ static Map<String, List<String>> extractJavaHeaders(Request request) { return OkHeaders.toMultimap(request.headers(), null); }
@Override public Map<String, List<String>> getHeaderFields() { return OkHeaders.toMultimap(response.headers(), StatusLine.get(response).toString()); }
public Builder setResponseSource(ResponseSource responseSource) { return header(OkHeaders.RESPONSE_SOURCE, responseSource + " " + statusLine.code()); }