gpt4 book ai didi

android - OkHttp 库 - 简单帖子上的 NetworkOnMainThreadException

转载 作者:IT老高 更新时间:2023-10-28 22:16:26 28 4
gpt4 key购买 nike

我想使用 OkHttp Android中的网络库。我从他们网站上写的简单帖子示例开始:

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 库应该已经处理了这个问题。我做错了吗?

最佳答案

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

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)中处理:

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:

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/recipes/

关于android - OkHttp 库 - 简单帖子上的 NetworkOnMainThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135338/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com