Find some examples of usage below (two first are taken from their documentation).
GET request:
GET request:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
POST request:
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();
}
This is my implementation of methods for HTTP calls.
private JSONObject request(String path, String method, String body) throws ApiException {
Builder builder = new Request.Builder()
.url(baseUrl + path.replaceAll("^/", ""));
if (method.equals("POST")) {
builder.post(RequestBody.create(JSON, body));
}
else if (method.equals("DELETE")) {
builder.delete();
}
try {
Response httpResponse = httpClient.newCall(builder.build()).execute();
if (httpResponse.code() != 200) {
throw new ApiException(httpResponse.body().string());
}
String httpResponseBody = httpResponse.body().string();
System.out.println("ApiClient.request(" + path + "): " + httpResponseBody);
return (JSONObject)JSONValue.parse(httpResponseBody);
}
catch (IOException e) {
throw new ApiException(e.getMessage());
}
}
public JSONObject get(String resource, Map<String, String> params) throws ApiException {
return request(resource + "?" + urlEncodeUTF8(params), "GET", "");
}
public JSONObject post(String path, String body) throws ApiException {
return request(path, "POST", body);
}