为什么我在同步调用的 OkHttpClient() 响应调用上得到 android.os.NetworkOnMainThreadException?

问题描述 投票:0回答:1

根据文档

,我正在使用 OkHttpClient() 创建与 Web 服务器的同步连接

标题

private void sendGetRequest(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    // The following call throws a android.os.NetworkOnMainThreadException. 
    String responseBody = ((Response) response).body().string();
    // Process response.
}

由于连接是同步的,我不应该得到这个错误。有没有人能够在同步模式下使用 OkHttpClient()?

okhttp synchronous
1个回答
0
投票

在 SO 上发布我的问题后,我问了 ChatGPT 同样的问题,经过短暂的来回交流,我明白了为什么我会收到错误。然后我要求使用 AsyncTask 的替代解决方案,它建议使用 Retrofit 和 Volley。我和 Volley 一起去了,并在大约半小时内完成了实施。谢谢你,ChatGPT!

© www.soinside.com 2019 - 2024. All rights reserved.