使用FutureTask调用RESTful Web服务

时间:2014-11-17 12:10:29

标签: android multithreading web-services future futuretask

目前我正在使用AsyncHttpClient从Android设备调用RESTfull WebService,它运行正常。我想使用FutureTask对其进行优化,因为它允许我们检查线程是否已完成和填充。我现在使用的代码是这样的

AsyncHttpClient client = new AsyncHttpClient();
    try {
        client.post(applicationContext, "http://" + ip
                + ":8080/MyWebService/jaxrs/service/getData",
                new StringEntity("String"), "application/json",
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String response) {


                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        System.err.println("Exception: "
                                    + e.getMessage());
                    }

                });
    } catch (Exception e) {
        System.err.println("Exception: "
                                    + e.getMessage());
    }

我所知道的是在 Callable< 调用函数内部生成AsyncHttpClient class> ,调用WebService。

这里我很困惑,因为AsyncHttpClient也在一个线程中运行。我应该如何使用 Future 调用Web服务。

注意:   - 线程初学者。

1 个答案:

答案 0 :(得分:2)

Future + HttpClient = AsyncHttpClient

如果调用AsyncHttpClient.onSuccess()或AsyncHttpClient.onFailure(),则意味着线程已完成,或者它仍在运行(阻塞)。

== EDIT ==

好的,这里有一个例子。请在java doc。中阅读有关FutureTask和Executor的更多信息。

FutureTask<HttpResult> future = new FutureTask<HttpResult>(new Callable<HttpResult>() {
        // GET A HTTP RESULT IN ANOTHER THREAD
        @Override
        public HttpResult call() throws Exception {
            HttpClient httpClient =new HttpClient();
            //set url, http method and params
            HttpResult result = httpClient.getResult(); // sync request, it costs a long time.  
            return result;
        }
    }){
        // FutureTask.DONE() WILL BE CALLED ASYNCHRONOUSLY
        @Override
        protected void done() {
            try {
                HttpResult result=get();
                //read the result
            } catch (InterruptedException e) {
                logger.error("", e);
            } catch (ExecutionException e) {
                logger.error("", e);
            }

        }
    };