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 run() throws Exception { Request request = new Request.Builder() .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build(); try (Response response = client.newCall(request).execute()) { System.out.println("Response completed: " + response); } }
public void run() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @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()); } } }); }
@Override protected void get(Call.Factory client) throws Exception { client.newCall(new Request.Builder().url(baseUrl()).build()).execute().body().close(); }
private void run() { OkHttpClient client = new OkHttpClient.Builder() .readTimeout(0, TimeUnit.MILLISECONDS) .build(); Request request = new Request.Builder() .url("ws://echo.websocket.org") .build(); client.newWebSocket(request, this); // Trigger shutdown of the dispatcher's executor so this process can exit cleanly. client.dispatcher().executorService().shutdown(); }
/** Create a synthetic successful response with {@code body} as the deserialized body. */ public static <T> Response<T> success(@Nullable T body) { return success(body, new okhttp3.Response.Builder() // .code(200) .message("OK") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
@Override public Request request() { if (response != null) { return response.raw().request(); } return new Request.Builder() .url("http://localhost") .build(); } }
/** See https://api.slack.com/rtm. */ public WebSocket rtm(HttpUrl url, WebSocketListener listener) { return httpClient.newWebSocket(new Request.Builder() .url(url) .build(), listener); }
private Request buildRequest(String hostname, int type) { Request.Builder requestBuilder = new Request.Builder().header("Accept", DNS_MESSAGE.toString()); ByteString query = DnsRecordCodec.encodeQuery(hostname, type); if (post) { requestBuilder = requestBuilder.url(url).post(RequestBody.create(DNS_MESSAGE, query)); } else { String encoded = query.base64Url().replace("=", ""); HttpUrl requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build(); requestBuilder = requestBuilder.url(requestUrl); } return requestBuilder.build(); }
/** * Create a synthetic error response with an HTTP status code of {@code code} and {@code body} * as the error body. */ public static <T> Response<T> error(int code, ResponseBody body) { if (code < 400) throw new IllegalArgumentException("code < 400: " + code); return error(body, new okhttp3.Response.Builder() // .code(code) .message("Response.error()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
private WebSocket newWebSocket(String path, WebSocketListener listener) { Request request = new Request.Builder().url(HOST + path).build(); return client.newWebSocket(request, listener); }
/** * Create a synthetic successful response using {@code headers} with {@code body} as the * deserialized body. */ public static <T> Response<T> success(@Nullable T body, Headers headers) { checkNotNull(headers, "headers == null"); return success(body, new okhttp3.Response.Builder() // .code(200) .message("OK") .protocol(Protocol.HTTP_1_1) .headers(headers) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
/** * Create a synthetic successful response with an HTTP status code of {@code code} and * {@code body} as the deserialized body. */ public static <T> Response<T> success(int code, @Nullable T body) { if (code < 200 || code >= 300) { throw new IllegalArgumentException("code < 200 or >= 300: " + code); } return success(body, new okhttp3.Response.Builder() // .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method) throws MalformedURLException { okhttp3.MediaType contentType = getContentType(headers); RequestBody body = (content.length > 0 || okhttp3.internal.http.HttpMethod.requiresRequestBody(method.name()) ? RequestBody.create(contentType, content) : null); Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body); headers.forEach((headerName, headerValues) -> { for (String headerValue : headerValues) { builder.addHeader(headerName, headerValue); } }); return builder.build(); }
@Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request(); String host = this.host; if (host != null) { HttpUrl newUrl = request.url().newBuilder() .host(host) .build(); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } }
Request createRequest() { Request.Builder request = new Request.Builder(); request.url(url); request.method(getRequestMethod(), getRequestBody()); if (headers != null) { for (String header : headers) { String[] parts = header.split(":", 2); request.header(parts[0], parts[1]); } } if (referer != null) { request.header("Referer", referer); } request.header("User-Agent", userAgent); return request.build(); }
@Override public void loadData(@NonNull Priority priority, @NonNull final DataCallback<? super InputStream> callback) { Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl()); for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) { String key = headerEntry.getKey(); requestBuilder.addHeader(key, headerEntry.getValue()); } Request request = requestBuilder.build(); this.callback = callback; call = client.newCall(request); call.enqueue(this); }
public Response response(DiskLruCache.Snapshot snapshot) { String contentType = responseHeaders.get("Content-Type"); String contentLength = responseHeaders.get("Content-Length"); Request cacheRequest = new Request.Builder() .url(url) .method(requestMethod, null) .headers(varyHeaders) .build(); return new Response.Builder() .request(cacheRequest) .protocol(protocol) .code(code) .message(message) .headers(responseHeaders) .body(new CacheResponseBody(snapshot, contentType, contentLength)) .handshake(handshake) .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(receivedResponseMillis) .build(); } }
/** * Creates an OkHttp {@link Request} from the supplied information. * * <p>This method allows a {@code null} value for {@code requestHeaders} for situations where a * connection is already connected and access to the headers has been lost. See {@link * java.net.HttpURLConnection#getRequestProperties()} for details. */ public static Request createOkRequest( URI uri, String requestMethod, Map<String, List<String>> requestHeaders) { // OkHttp's Call API requires a placeholder body; the real body will be streamed separately. RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod) ? Util.EMPTY_REQUEST : null; Request.Builder builder = new Request.Builder() .url(uri.toString()) .method(requestMethod, placeholderBody); if (requestHeaders != null) { Headers headers = extractOkHeaders(requestHeaders, null); builder.headers(headers); } return builder.build(); }