gpt4 book ai didi

java - okHttp NetworkOnMainThreadException 尽管有新线程

转载 作者:行者123 更新时间:2023-12-01 16:43:40 25 4
gpt4 key购买 nike

在 android studio 项目中,我使用 okhttp 发送 post 请求。

public void sentRequest(.... ....) {

RequestBody formBody = new FormBody.Builder().add("number", number).build();
Request request = new Request.Builder().url(serverBase + API_numberAvailabilityCheck).post(formBody).build();
call = client.newCall(request);

new Thread(new Runnable() {
@Override
public void run() {
final HashMap<String, Object> requestResult = new HashMap<>();
try {
final Response response = call.execute();
}
...........
...........
}
}).run();

}

但它在我调用 final Response response = call.execute(); 的地方抛出 NetworkOnMainThreadException 异常,尽管 new Thread 。为什么它会抛出异常?以及如何解决这个问题?

最佳答案

错误是

thread.run() 而不是 thread.start()

调用run()方法,代码在同一个线程中运行,而不启动新线程。

关于java - okHttp NetworkOnMainThreadException 尽管有新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337659/

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