canonical example by Tabnine
public void sendGetRequest(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); try (Response response = client.newCall(request).execute()) { String responseBody = response.body().string(); // ... do something with response } }
public void run() throws Exception { Request request = new Request.Builder() .url("https://publicobject.com/helloworld.txt") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } }
public void fetch(HttpUrl url) throws IOException { AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount); if (previous != null) hostnameCount = previous; if (hostnameCount.incrementAndGet() > 100) return; Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { String responseSource = response.networkResponse() != null ? ("(network: " + response.networkResponse().code() + " over " + response.protocol() + ")") : "(cache)"; int responseCode = response.code(); String contentType = response.header("Content-Type"); if (responseCode != 200 || contentType == null) { return; Document document = Jsoup.parse(response.body().string(), url.toString()); for (Element element : document.select("a[href]")) { String href = element.attr("href"); HttpUrl link = response.request().url().resolve(href); if (link == null) continue; // URL is either invalid or its scheme isn't http/https. queue.add(link.newBuilder().fragment(null).build());
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(); }
private static String responseSourceHeader(Response response) { if (response.networkResponse() == null) { if (response.cacheResponse() == null) { return "NONE"; } return "CACHE " + response.code(); } if (response.cacheResponse() == null) { return "NETWORK " + response.code(); } return "CONDITIONAL_CACHE " + response.networkResponse().code(); }
public static <T> JsonResponse<T> execute(JsonCodec<T> codec, OkHttpClient client, Request request) { try (Response response = client.newCall(request).execute()) { // TODO: fix in OkHttp: https://github.com/square/okhttp/issues/3111 if ((response.code() == 307) || (response.code() == 308)) { String location = response.header(LOCATION); if (location != null) { request = request.newBuilder().url(location).build(); return execute(codec, client, request); } } ResponseBody responseBody = requireNonNull(response.body()); String body = responseBody.string(); if (isJson(responseBody.contentType())) { return new JsonResponse<>(response.code(), response.message(), response.headers(), body, codec); } return new JsonResponse<>(response.code(), response.message(), response.headers(), body); } catch (IOException e) { // OkHttp throws this after clearing the interrupt status // TODO: remove after updating to Okio 1.15.0+ if ((e instanceof InterruptedIOException) && "thread interrupted".equals(e.getMessage())) { Thread.currentThread().interrupt(); } throw new UncheckedIOException(e); } }
/** * Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286 */ private Response followPostRedirect(Response response) throws IOException { String location = response.header("Location"); if (location == null) { throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url())); } HttpUrl url = response.request().url().resolve(location); // Don't follow redirects to unsupported protocols. if (url == null) { throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location)); } Request.Builder redirectRequest = response.request().newBuilder(); redirectRequest.post(response.request().body()); response.body().close(); return okHttpClient.newCall(redirectRequest.url(url).build()).execute(); }
public Optional<String> fetchFileIfNotModified(String url) throws IOException { final Request.Builder requestBuilder = new Request.Builder() .get() .url(url) .header("User-Agent", "Graylog (server)"); final String lastModified = this.lastLastModified.get().get(url); requestBuilder.header("If-Modified-Since", lastModified); final Call request = client.newCall(requestBuilder.build()); try (final Response response = request.execute()) { if (response.isSuccessful()) { final String lastModifiedHeader = response.header("Last-Modified", DateTime.now(DateTimeZone.UTC).toString()); final Map<String, String> newLastModified = new HashMap<>(this.lastLastModified.get()); newLastModified.put(url, lastModifiedHeader); this.lastLastModified.set(ImmutableMap.copyOf(newLastModified)); if (response.body() != null) { final String body = response.body().string(); return Optional.ofNullable(body); if (response.code() != 304) { throw new IOException("Request failed: " + response.message());
public void run() throws Exception { Request request = new Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gistJsonAdapter.fromJson(response.body().source()); for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue().content); } } }
/** like {@link #get(Request)} except doesn't throw unsupported on not found */ Response call(Request request) throws IOException { try (Response response = client.newCall(request).execute()) { if (!HttpHeaders.hasBody(response)) return response; // buffer response so tests can read it. Otherwise the finally block will drop it ResponseBody toReturn; try (ResponseBody body = response.body()) { Buffer buffer = new Buffer(); body.source().readAll(buffer); toReturn = ResponseBody.create(body.contentType(), body.contentLength(), buffer); } return response.newBuilder().body(toReturn).build(); } }
@Override public void onResponse(@NonNull Call call, @NonNull Response response) { responseBody = response.body(); if (response.isSuccessful()) { long contentLength = Preconditions.checkNotNull(responseBody).contentLength(); stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength); callback.onDataReady(stream); } else { callback.onLoadFailed(new HttpException(response.message(), response.code())); } }
private static Response stripBody(Response response) { return response != null && response.body() != null ? response.newBuilder().body(null).build() : response; }
@Override public Response intercept(Chain chain) throws IOException { Request userRequest = chain.request(); Request.Builder requestBuilder = userRequest.newBuilder(); requestBuilder.header("Content-Length", Long.toString(contentLength)); requestBuilder.removeHeader("Transfer-Encoding"); } else { requestBuilder.header("Transfer-Encoding", "chunked"); if (userRequest.header("Host") == null) { requestBuilder.header("Host", hostHeader(userRequest.url(), false)); Response networkResponse = chain.proceed(requestBuilder.build()); HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers()); Response.Builder responseBuilder = networkResponse.newBuilder() .request(userRequest); && "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); String contentType = networkResponse.header("Content-Type"); responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
private List<InetAddress> readResponse(String hostname, Response response) throws Exception { if (response.cacheResponse() == null && response.protocol() != Protocol.HTTP_2) { Platform.get().log(Platform.WARN, "Incorrect protocol: " + response.protocol(), null); } try { if (!response.isSuccessful()) { throw new IOException("response: " + response.code() + " " + response.message()); } ResponseBody body = response.body(); if (body.contentLength() > MAX_RESPONSE_SIZE) { throw new IOException("response size exceeds limit (" + MAX_RESPONSE_SIZE + " bytes): " + body.contentLength() + " bytes"); } ByteString responseBytes = body.source().readByteString(); return DnsRecordCodec.decodeAnswers(hostname, responseBytes); } finally { response.close(); } }
private @Nullable Response getCacheOnlyResponse(Request request) { if (!post && client.cache() != null) { try { Request cacheRequest = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build(); Response cacheResponse = client.newCall(cacheRequest).execute(); if (cacheResponse.code() != 504) { return cacheResponse; } } catch (IOException ioe) { // Failures are ignored as we can fallback to the network // and hopefully repopulate the cache. } } return null; }
@Override public Response metaRefresh(String nextUrl) throws Exception { HttpUrl lastUrl = lastResponse.request().url(); if (!nextUrl.startsWith("http")){ String prefix = lastUrl.scheme()+"://"+lastUrl.host()+lastUrl.encodedPath(); nextUrl = prefix + nextUrl; } logger.info("Seimi refresh url to={} from={}",nextUrl,lastUrl.toString()); currentRequestBuilder.url(nextUrl); lastResponse = okHttpClient.newCall(currentRequestBuilder.build()).execute(); return renderResponse(lastResponse,currentRequest); }
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")); } }
private static HttpResponse transformResponse(Response response) { int code = response.code(); String message = response.message(); BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message); ResponseBody body = response.body(); InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength()); httpResponse.setEntity(entity); Headers headers = response.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String name = headers.name(i); String value = headers.value(i); httpResponse.addHeader(name, value); if ("Content-Type".equalsIgnoreCase(name)) { entity.setContentType(value); } else if ("Content-Encoding".equalsIgnoreCase(name)) { entity.setContentEncoding(value); } } return httpResponse; }
@Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(responseBody.string()); } } });