OkHttp Library – NetworkOnMainThreadException on simple post

You should use OkHttp’s async method.

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

Call post(String url, String json, Callback callback) {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Call call = client.newCall(request);
  call.enqueue(callback);
  return call;
}

And then your response would be handled in the callback (OkHttp 2.x):

post("http://www.roundsapp.com/post", json, new Callback() {
  @Override
  public void onFailure(Request request, Throwable throwable) {
     // Something went wrong
  }

  @Override public void onResponse(Response response) throws IOException {
    if (response.isSuccessful()) {
       String responseStr = response.body().string();
       // Do what you want to do with the response.
    } else {
       // Request not successful
    }
  }
});

Or OkHttp 3.x/4.x:

post("http://www.roundsapp.com/post", "", new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // Something went wrong
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                // Do what you want to do with the response.
            } else {
                // Request not successful
            }
        }
    });

Take a look at their recipes for more examples: http://square.github.io/okhttp/recipes/

Leave a Comment