CacheHttpURLConnection(Response response) { super(response.request().url().url()); this.request = response.request(); this.response = response; // Configure URLConnection inherited fields. this.connected = true; this.doOutput = request.body() != null; this.doInput = true; this.useCaches = true; // Configure HttpUrlConnection inherited fields. this.method = request.method(); }
@Override public Request request() { if (response != null) { return response.raw().request(); } return new Request.Builder() .url("http://localhost") .build(); } }
public void run() throws Exception { Request request = new Request.Builder() .url("https://publicobject.com/helloworld.txt") .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.request().header("Date")); } }
@Override public Request authenticate(Route route, Response response) throws IOException { if (response.request().header("Authorization") != null) { return null; // Give up, we've already attempted to authenticate. } System.out.println("Authenticating for response: " + response); System.out.println("Challenges: " + response.challenges()); String credential = Credentials.basic("jesse", "password1"); return response.request().newBuilder() .header("Authorization", credential) .build(); } })
@Override public @Nullable Uri getUri() { return response == null ? null : Uri.parse(response.request().url().toString()); }
@Override public void onResponse(Call call, Response response) { synchronized (lock) { this.response = response; this.handshake = response.handshake(); this.url = response.request().url().url(); lock.notifyAll(); } }
Entry(Response response) { this.url = response.request().url().toString(); this.varyHeaders = HttpHeaders.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(); this.sentRequestMillis = response.sentRequestAtMillis(); this.receivedResponseMillis = response.receivedResponseAtMillis(); }
@Override public Request authenticate(Route route, Response response) { // skip if we already tried or were not asked for Kerberos if (response.request().headers(AUTHORIZATION).stream().anyMatch(SpnegoHandler::isNegotiate) || response.headers(WWW_AUTHENTICATE).stream().noneMatch(SpnegoHandler::isNegotiate)) { return null; } return authenticate(response.request()); }
/** Returns true if the response must have a (possibly 0-length) body. See RFC 7231. */ public static boolean hasBody(Response response) { // HEAD requests never yield a body regardless of the response headers. if (response.request().method().equals("HEAD")) { return false; } int responseCode = response.code(); if ((responseCode < HTTP_CONTINUE || responseCode >= 200) && responseCode != HTTP_NO_CONTENT && responseCode != HTTP_NOT_MODIFIED) { return true; } // If the Content-Length or Transfer-Encoding headers disagree with the response code, the // response is malformed. For best compatibility, we honor the headers. if (contentLength(response) != -1 || "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) { return true; } return false; }
public static void processResponse(Response response, EventSourceListener listener) { RealEventSource eventSource = new RealEventSource(response.request(), listener); eventSource.processResponse(response); }
public static void main(String... args) throws IOException { HostSelectionInterceptor hostSelectionInterceptor = new HostSelectionInterceptor(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(hostSelectionInterceptor) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://www.github.com/") .callFactory(okHttpClient) .build(); Pop pop = retrofit.create(Pop.class); Response<ResponseBody> response1 = pop.robots().execute(); System.out.println("Response from: " + response1.raw().request().url()); System.out.println(response1.body().string()); hostSelectionInterceptor.setHost("www.pepsi.com"); Response<ResponseBody> response2 = pop.robots().execute(); System.out.println("Response from: " + response2.raw().request().url()); System.out.println(response2.body().string()); } }
/** * Returns the subset of the headers in {@code response}'s request that impact the content of * response's body. */ public static Headers varyHeaders(Response response) { // Use the request headers sent over the network, since that's what the // response varies on. Otherwise OkHttp-supplied headers like // "Accept-Encoding: gzip" may be lost. Headers requestHeaders = response.networkResponse().request().headers(); Headers responseHeaders = response.headers(); return varyHeaders(requestHeaders, responseHeaders); }
@Override public void onResponse(Call<Page> call, Response<Page> response) { if (!response.isSuccessful()) { System.out.println(call.request().url() + ": failed: " + response.code()); return; } // Print this page's URL and title. Page page = response.body(); HttpUrl base = response.raw().request().url(); System.out.println(base + ": " + page.title); // Enqueue its links for visiting. for (String link : page.links) { HttpUrl linkUrl = base.resolve(link); if (linkUrl != null && fetchedUrls.add(linkUrl)) { crawlPage(linkUrl); } } }
@Override public CacheRequest put(Response response) throws IOException { URI uri = response.request().url().uri(); HttpURLConnection connection = JavaApiConverter.createJavaUrlConnectionForCachePut(response); final java.net.CacheRequest request = delegate.put(uri, connection); if (request == null) { return null; } return new CacheRequest() { @Override public Sink body() throws IOException { OutputStream body = request.getBody(); return body != null ? Okio.sink(body) : null; } @Override public void abort() { request.abort(); } }; }
/** * Returns the number of milliseconds that the response was fresh for, starting from the served * date. */ private long computeFreshnessLifetime() { CacheControl responseCaching = cacheResponse.cacheControl(); if (responseCaching.maxAgeSeconds() != -1) { return SECONDS.toMillis(responseCaching.maxAgeSeconds()); } else if (expires != null) { long servedMillis = servedDate != null ? servedDate.getTime() : receivedResponseMillis; long delta = expires.getTime() - servedMillis; return delta > 0 ? delta : 0; } else if (lastModified != null && cacheResponse.request().url().query() == null) { // As recommended by the HTTP RFC and implemented in Firefox, the // max age of a document should be defaulted to 10% of the // document's age at the time it was served. Default expiration // dates aren't used for URIs containing a query. long servedMillis = servedDate != null ? servedDate.getTime() : sentRequestMillis; long delta = servedMillis - lastModified.getTime(); return delta > 0 ? (delta / 10) : 0; } return 0; }
/** * Returns true if an HTTP request for {@code followUp} can reuse the connection used by this * engine. */ private boolean sameConnection(Response response, HttpUrl followUp) { HttpUrl url = response.request().url(); return url.host().equals(followUp.host()) && url.port() == followUp.port() && url.scheme().equals(followUp.scheme()); } }
@Nullable CacheRequest put(Response response) { String requestMethod = response.request().method(); if (HttpMethod.invalidatesCache(response.request().method())) { try { remove(response.request()); } catch (IOException ignored) { DiskLruCache.Editor editor = null; try { editor = cache.edit(key(response.request().url())); if (editor == null) { return null;
url = response.request().url().url();
@Override public ResponseBody openResponseBody(Response response) throws IOException { streamAllocation.eventListener.responseBodyStart(streamAllocation.call); String contentType = response.header("Content-Type"); if (!HttpHeaders.hasBody(response)) { Source source = newFixedLengthSource(0); return new RealResponseBody(contentType, 0, Okio.buffer(source)); } if ("chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) { Source source = newChunkedSource(response.request().url()); return new RealResponseBody(contentType, -1L, Okio.buffer(source)); } long contentLength = HttpHeaders.contentLength(response); if (contentLength != -1) { Source source = newFixedLengthSource(contentLength); return new RealResponseBody(contentType, contentLength, Okio.buffer(source)); } return new RealResponseBody(contentType, -1L, Okio.buffer(newUnknownLengthSource())); }
/** * Creates an {@link java.net.HttpURLConnection} of the correct subclass from the supplied OkHttp * {@link Response}. */ static HttpURLConnection createJavaUrlConnectionForCachePut(Response okResponse) { okResponse = okResponse.newBuilder() .body(null) .headers(withSyntheticHeaders(okResponse)) .build(); Request request = okResponse.request(); // Create an object of the correct class in case the ResponseCache uses instanceof. if (request.isHttps()) { return new CacheHttpsURLConnection(new CacheHttpURLConnection(okResponse)); } else { return new CacheHttpURLConnection(okResponse); } }