2

我的if (httpResponse == null)块无法运行。以前如何实施HttpResponse httpResponse = httpClient.execute(httpPost);

请告诉我如何做到这一点。

    public class XMLParser {
    private Activity activity = null;
    // constructor
    public XMLParser(Activity act) {
        activity = act;
    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                AlertDialog.Builder builder = new AlertDialog.Builder( activity ); //<<-- This part throws an exception " ThreadPoolExecutor "
                builder.setMessage( "Host not found" )
                        .setCancelable(false)
                        .setPositiveButton("Exit",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        System.exit(0);
                                    }

                                });
                AlertDialog alert = builder.create();
                alert.show();
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}
4

2 回答 2

2

当出现问题时,execute不会返回 null 而是抛出异常。例如,当找不到主机时,它会抛出一个UnknownHostException. 此异常是 IOException 的子类。

您的代码旨在 'catch' IOException。但是当这种情况发生时,你只打印一个堆栈跟踪(这可以在你的 LogCat 中以橙色看到)并且什么都不做。所以接下来,'return xml' 语句被执行并且你的方法结束。

因此,如果您想“捕捉”主机不存在的情况,您可以像下面这样重写它。要捕获更多错误,您可能应该计算出IOExceptioncatch 块。请确保您了解发生的情况以及异常处理的工作原理。

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnknownHostException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder( activity );
        builder.setMessage( "Host not found" )
                .setCancelable(false)
                .setPositiveButton("Exit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                System.exit(0);
                            }

                        });
        AlertDialog alert = builder.create();
        alert.show();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // return XML
    return xml;
}
于 2012-08-26T12:24:52.603 回答
-1

我不认为来自服务器的无响应会产生空响应。你能调试一下在运行时探索 httpResponse 的价值吗?

于 2012-08-26T11:26:47.247 回答