Android 需要一个示例来展示如何执行异步 HTTP 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2316766/
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-20 05:22:31  来源:igfitidea点击:

Need an example showing how to do async HTTP requests

androidhttpmultithreadingasynchronoustask

提问by Eno

Im using a web service, so I want to use an async thread for the HTTP authentication request and another thread later to make additional service requests while my main thread runs.

我正在使用 Web 服务,因此我想使用异步线程进行 HTTP 身份验证请求,稍后使用另一个线程在主线程运行时发出其他服务请求。

Would like to see a good example of how to do this and how to show busy messages somehow in main app. How does the main app know when the thread finished? And what if my thread encounters exceptions, how do I deal with that?

想看到一个很好的例子,说明如何做到这一点以及如何在主应用程序中以某种方式显示繁忙的消息。主应用程序如何知道线程何时完成?如果我的线程遇到异常怎么办?

HTTP requests are sent later, use the same cookies setup up by the first auth request, so will the later requests pick up the same cookies and just work?

HTTP 请求稍后发送,使用第一个身份验证请求设置的相同 cookie,那么后面的请求会选择相同的 cookie 并正常工作吗?

回答by koush

AndroidAsync library I wrote to handle this automatically, it will run in the background and reinvoke onto the UI thread:

我编写的 AndroidAsync 库用于自动处理此问题,它将在后台运行并重新调用 UI 线程:

https://github.com/koush/AndroidAsync

https://github.com/koush/AndroidAsync

// url is the URL to download. The callback will be invoked on the UI thread
// once the download is complete.
AsyncHttpClient.getDefaultInstance().get(url, new AsyncHttpClient.StringCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, String result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a string: " + result);
    }
});