OkHttp Library - NetworkOnMainThreadException on simple post

Solution 1:

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/

Solution 2:

According to the OkHttp docs: It supports both synchronous blocking calls and async calls with callbacks. Your example is on main thread and Android since version 3.0 throws that exception if you try to do network calls on main thread

Better option is to use it together with retrofit and Gson: http://square.github.io/retrofit/ https://code.google.com/p/google-gson/

Here are the examples: http://engineering.meetme.com/2014/03/best-practices-for-consuming-apis-on-android/ http://heriman.net/?p=5