Android Okhttp 异步调用 [英] Android Okhttp asynchronous calls

查看:38
本文介绍了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<> 的新类?

I've 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<>?

推荐答案

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

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;

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆