Basic usage example

suggest change

One approach is to wrap OkHttp in a class such as HttpClient, with a method for each common HTTP verb: post, get, put, and delete. Implementing an interface makes it easier to swap the implementation:

public class HttpClient implements HttpClientInterface{

private static final String TAG = HttpClient.class.getSimpleName();
public static final MediaType JSON
        = MediaType.parse("application/json; charset=utf-8");

OkHttpClient httpClient = new OkHttpClient();

@Override
public String post(String url, String json) throws IOException {
    Log.i(TAG, "Sending a post request with body:\n" + json + "\n to URL: " + url);

    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    Response response = httpClient.newCall(request).execute();
    try {
        return response.body().string();
    } finally {
        response.close();
    }
}
}

put, get, and delete differ mainly in the builder call, such as .put(body) or .get(). Call the method with a URL and, for verbs that have a body, a JSON payload. The method returns the response body as a string. If that body is JSON, build a JSONObject from it. The constructor throws JSONException when the text is not JSON.

String response = httpClient.post(MY_URL, JSON_PAYLOAD);
JSONObject json = new JSONObject(response);
// continue to parse the response according to its structure

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents