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 static void main(String... args) throws Exception { OkHttpClient client = new OkHttpClient(); // Create request for remote resource. Request request = new Request.Builder() .url(ENDPOINT) .build(); // Execute the request and retrieve the response. try (Response response = client.newCall(request).execute()) { // Deserialize HTTP response to concrete type. ResponseBody body = response.body(); List<Contributor> contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source()); // Sort list by the most contributions. Collections.sort(contributors, (c1, c2) -> c2.contributions - c1.contributions); // Output list of contributors. for (Contributor contributor : contributors) { System.out.println(contributor.login + ": " + contributor.contributions); } } }
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); }
private static Response call(String url) throws IOException { Request request = new Request.Builder().get().url(url).build(); return new OkHttpClient().newCall(request).execute(); }
public static void sendOkHttpRequest(String address, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); }
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()); } } }); }
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(); }
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(); }