本文介绍了Android Okhttp异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的api调用是在点击按钮时发生的,我收到了以下 android.os.NetworkOnMainThreadException 。我明白这是因为我在主线程上尝试网络调用,但我也在努力找到一个关于如何使这个代码使用另一个线程(异步调用)的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).

@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();

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

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<>??

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

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

推荐答案

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

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

&这样称呼:

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

这篇关于Android Okhttp异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:45