需要一个示例展示如何进行异步HTTP请求。

6
我正在使用一个Web服务,因此我想使用异步线程进行HTTP身份验证请求,并在主线程运行时稍后使用另一个线程进行其他服务请求。
我想看到一个很好的例子,演示如何做到这一点,并以某种方式在主应用程序中显示忙碌消息。主应用程序如何知道线程何时完成?如果我的线程遇到异常,该如何处理?
稍后发送的HTTP请求,使用第一个身份验证请求设置的相同cookie,所以后续请求会获取相同的cookie并正常工作吗?
3个回答



1

我编写了一个与Android相关的异步库,用于自动处理此问题。它将在后台运行并重新调用UI线程:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接