Android HttpClient作为AsyncTask在执行请求时崩溃

时间:2016-04-07 12:46:12

标签: android http asynchronous

我正在尝试执行请求并将响应作为异步任务返回。 但不幸的是它没有捕捉异常崩溃:( 这是代码。调用异步的类:

public class HttpUtilz{

HttpGet getRequest;

public NodeList executeGetAndReceiveNodeList(String url, String xpath)throws XPathExpressionException,IOException,ParserConfigurationException,SAXException{
    getRequest=new HttpGet(url);
    HttpResponse response = (HttpResponse) new RetrieveAsyncResp().execute(getRequest);
    InputStream inputStream = response.getEntity().getContent();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    Document doc = builder.parse(inputStream);
    doc.getDocumentElement().normalize();
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath=xPathFactory.newXPath();
    XPathExpression xPathExpression = xPath.compile(xpath);
    return (NodeList)xPathExpression.evaluate(doc, XPathConstants.NODESET);
}

}

执行异步:

public class RetrieveAsyncResp extends AsyncTask<HttpGet, String, HttpResponse> {

@Override
protected void onPreExecute(){
    super.onPreExecute();
}


@Override
protected HttpResponse doInBackground(HttpGet... get) {
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    try {
        response = client.execute(get[0]);
    }catch (IOException e){
        e.printStackTrace();
        response=null;
    }
    return response;
}
@Override
protected void onPostExecute(HttpResponse response){
    super.onPostExecute(response);
}

}

我正在通过下一个测试: String url =“http://new-rutor.org/search/batman%20v%20superman”; String xpath =“// div [@ id ='index'] / table / tbody / tr / td [2] / a [2]”;

模拟器为我提供的唯一内容是:

04-07 15:49:21.796    8396-8396/torrentz.com.torrentforme D/OpenGLRenderer﹕ Enabling debug mode 0
04-07 15:49:33.016    8396-8396/torrentz.com.torrentforme D/AndroidRuntime﹕ Shutting down VM
04-07 15:49:33.016    8396-8396/torrentz.com.torrentforme W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4d6eb20)

我很感激任何帮助/建议

1 个答案:

答案 0 :(得分:3)

您正在尝试在安排异步任务后立即阅读response

HttpResponse response = (HttpResponse) new RetrieveAsyncResp().execute(getRequest); // task being ca
InputStream inputStream = response.getEntity().getContent();

异步任务在后台线程上工作,所以在调用execute后,控制权移动到下一行,到那时你就不会得到你的回复。

尝试在response的{​​{1}}中移动解析onPostExecute的代码。

此外,我不知道这是如何工作的

async task

您的IDE将显示HttpResponse response = (HttpResponse) new RetrieveAsyncResp().execute(getRequest); 错误。