我想获得异步获取响应(Google App Engine)

时间:2011-07-02 13:12:45

标签: google-app-engine servlets

我在Google App Engine上制作Web应用程序,并使用AsyncURLFetch Api。

但是,我无法得到回应。请帮帮我......

Searc.java

private ArrayList<Future<HTTPResponse>> fetchURL() {
    ArrayList<Future<HTTPResponse>> futureList = new ArrayList<Future<HTTPResponse>>();

    for (SearchResult searchResult : searchResultList) {
        if (!searchResult.isEmpty()) {
            for (WebPage webPage : searchResult.getWebPageArray()) {
                try {
                    URL url = new URL(
                            "http://myapi.appspot.com/htmlparser?url="
                                    + webPage.getPageURL());
                    URLFetchService us = URLFetchServiceFactory
                            .getURLFetchService();
                    futureList.add(us.fetchAsync(url));
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    return futureList;
}

private ArrayList<HTTPResponse> getFetchResult(
        ArrayList<Future<HTTPResponse>> futureList) {
    ArrayList<HTTPResponse> responseList = new ArrayList<HTTPResponse>();
    try {
        for (Future<HTTPResponse> future : futureList) {
            if (future.isDone()) {
                log.info("future calls get");
                HTTPResponse resp = future.get();
                responseList.add(resp);
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        log.info(e.getMessage());
    } catch (ExecutionException e) {
        e.printStackTrace();
        log.info(e.getMessage());
    }
    return responseList;
}

HTMLParser.java

public class HTMLParser extends HttpServlet{
protected static Logger log = LoggerFactory.getLogger(HTMLParser.class);

private PrintWriter writer;
private URL paramURL;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    resp.setContentType("text/html; charset=utf8");
    writer = resp.getWriter();
    getParameter(req);
    viewTest();
}

private void getParameter(HttpServletRequest req){
    paramURL = getURL(req);
}

private URL getURL(HttpServletRequest req){
    try {
        URL url;
        url = new URL(req.getParameter("url"));
        return url;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}


private void viewTest(){
    writer.println(paramURL);
    log.info(paramURL.toString());
}}

future.isDone()是“假”

我做了什么让“真实”?

1 个答案:

答案 0 :(得分:0)

您是否阅读了Java Futures上的文档? future.isDone()将不会阻止,并且将返回False直到将来执行完毕。要获得所有异步调用的结果,您应该无条件地在每个调用上调用future.get()