【问题标题】:Android Okhttp asynchronous callsAndroid Okhttp 异步调用
【发布时间】:2016-04-30 06:44:43
【问题描述】:

我正在尝试使用 Okhttp 库通过 API 将我的 android 应用程序连接到我的服务器。

我的 API 调用发生在单击按钮时,我收到以下 android.os.NetworkOnMainThreadException。我知道这是因为我正在尝试在主线程上进行网络调用,但我也在努力在 Android 上找到一个干净的解决方案,以了解如何让这段代码使用另一个线程(异步调用)。

@Override
public void onClick(View v) {
    switch (v.getId()){
        //if login button is clicked
        case R.id.btLogin:
            try {
                String getResponse = doGetRequest("http://myurl/api/");
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
    }
}

String doGetRequest(String url) throws IOException{
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();

}

上面是我的代码,正在抛出异常就行了

Response response = client.newCall(request).execute();

我还读到 Okhhtp 支持异步请求,但我真的找不到适用于 Android 的干净解决方案,因为大多数人似乎都在使用一个使用 AsyncTask 的新类?

【问题讨论】:

    标签: java android api asynchronous okhttp


    【解决方案1】:

    要发送异步请求,请使用:

    void doGetRequest(String url) throws IOException{
        Request request = new Request.Builder()
                .url(url)
                .build();
    
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(final Call call, IOException e) {
                        // Error
    
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // For the example, you can show an error dialog or a toast
                                // on the main UI thread
                            }
                        });
                    }
    
                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        String res = response.body().string();
    
                        // Do something with the response
                    }
                });
    }
    

    &这样称呼它:

    case R.id.btLogin:
        try {
            doGetRequest("http://myurl/api/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    

    【讨论】:

    • try {...} catch (IOException e) {...}当然不需要doGetRequest(String url) throws IOException{
    • @V.Kalyuzhnyu Try.. catch 将处理由doGetRequestIOException 抛出的错误
    • String res = response.body().string(); 如果响应体很大并且无法立即使用,则将阻塞(因此可能希望在单独的线程池中进行阻塞操作)。另外 - 最好将其包装在 try (Response res = response) 中以确保响应已关闭,例如。里面没有尸体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 2016-07-09
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2023-04-03
    • 2020-04-30
    相关资源
    最近更新 更多