【问题标题】:Android HttpResponseAndroid HttpResponse
【发布时间】:2012-08-21 05:11:48
【问题描述】:

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

【问题讨论】:

    标签: android httpresponse


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我的 AlertDialog.Builder builder = new AlertDialog.Builder(activity);抛出异常“ThreadPoolExecutor”
    • 感谢您的回答。现在您已经更改了代码,您的问题有点令人困惑(对于找到此页面的其他人)。下次你应该记住这一点。另外,我看到您现在将错误代码放在SAXException 中,如果在 XML 解析期间出现问题,就会发生这种情况。请注意,每个 catch 块都会捕获不同的异常。
    • 另外,ThreadPoolExecutor 也不是异常,它可能是把它扔到堆栈上的那个。
    【解决方案2】:

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

    【讨论】:

    • 您有什么建议可以让我检查服务器无响应吗?我会告诉你我的完整代码。
    • 是的,只是尝试访问一个不存在的 url。 (即:android_novice.com
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2012-04-27
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多