OkHttp图书馆 - NetworkOnMainThreadException简单的后上图书馆、简单、OkHttp、NetworkOnMainThreadException

2023-09-04 23:29:06 作者:钢茎混凝凸

我想使用 OkHttp 库联网的Andr​​oid。 我开始用简单的例子后写在他们的网站:

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) throws IOException {
  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:

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

看看他们的食谱为更多的例子:https://github.com/square/okhttp/wiki/Recipes