OkHttp 库 - 简单帖子上的 NetworkOnMainThreadException [英] OkHttp Library - NetworkOnMainThreadException on simple post

查看:27
本文介绍了OkHttp 库 - 简单帖子上的 NetworkOnMainThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Android 中使用 OkHttp 库进行网络连接.我从他们网站上写的简单帖子示例开始:

I want to use OkHttp library for networking in Android. I started with the simple post example as written in their website:

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();
}

通过这个调用:

String response = post("http://www.roundsapp.com/post", json);

此调用以 NetworkOnMainThreadException 结束.
我可以用 AsyncTask 包装调用,但据我从示例中了解到,OkHttp 库应该已经处理了这个问题.我做错了什么吗?

This call ends with NetworkOnMainThreadException.
I could wrap the call with an AsyncTask, but as far as I understand from the examples, the OkHttp library should have already taken care of that.. Am I doing something wrong?

推荐答案

你应该使用 OkHttp 的异步方法.

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;
}

然后您的响应将在回调中处理(OkHttp 2.x):

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
    }
  }
});

或者 OkHttp 3.x/4.x:

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
            }
        }
    });

查看他们的食谱以获得更多示例:http://square.github.io/okhttp/食谱/

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

这篇关于OkHttp 库 - 简单帖子上的 NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆