Java Android Okhttp 异步调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34967505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:11:30  来源:igfitidea点击:

Android Okhttp asynchronous calls

javaandroidapiasynchronousokhttp

提问by jjharrison

I am attempting to use the Okhttp library to connect my android app to my server via API.

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

My api call is happening on a button click and I am receiving the following android.os.NetworkOnMainThreadException. I understand that this is due the fact I am attempting network calls on the main thread but I am also struggling to find a clean solution on android as to how make this code use another thread (async calls).

我的 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();

}

Above is my code, and the exception is being thrown on the line

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

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

Ive also read that Okhhtp supports Async requests but I really can't find a clean solution for android as most seem to use a new class that uses AsyncTask<>??

我也读过 Okhhtp 支持异步请求,但我真的找不到一个干净的 android 解决方案,因为大多数人似乎使用一个使用AsyncTask<>的新类?

Any help or suggestions are much appreciated, thankyou...

非常感谢任何帮助或建议,谢谢...

采纳答案by Mohammed Aouf Zouag

To send an asynchronous request, use this:

要发送异步请求,请使用以下命令:

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

& call it this way:

&这样称呼它:

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