在Android中从URL获取XML会显示null错误

时间:2016-12-29 16:36:12

标签: android xml http get

我正在尝试使用Android中的HTTP Get方法从网址获取XML文件。当我在浏览器中输入url时,我得到了XML文件。但是,当我尝试在Android中使用HttpURLConnection时,输入流始终为null。我想弄清楚问题但是徒劳无功。我想帮助理解这个问题。
这是我的代码:
XML文件

<?xml version="1.0" encoding="UTF-8"?>
<item>
    <log>27.1823000000</log>
    <lat>88.5012200000</lat>
</item>

异步任务

private class GetOnlineData extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... voids){
            String latlog=null;

            // Accessing link to obtain XML file
            try{
                URL url = new URL(link);
                HttpURLConnection htc = (HttpURLConnection) url.openConnection();
                inputStream = htc.getInputStream();
            }catch(Exception e){}

            // Parsing XML data from input stream
            if(inputStream!=null){
                try {
                    DocumentBuilderFactory xmlparser = DocumentBuilderFactory.newInstance();
                    DocumentBuilder dBuilder = xmlparser.newDocumentBuilder();
                    Document dc = dBuilder.parse(inputStream);

                    Element ele = dc.getDocumentElement();
                    ele.normalize();

                    NodeList nodeList = dc.getElementsByTagName("item");

                    for (int i=0; i<nodeList.getLength(); i++){
                        Node node = nodeList.item(i);
                        if(node.getNodeType() == Node.ELEMENT_NODE){
                            Element ele2 = (Element) node;
                            latlog = "Longitude: "+getValue("log",ele2)+"\n";
                            latlog += "Latitude: "+getValue("lat",ele2);
                        }
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }

            return latlog;
        }

        @Override
        protected void onPostExecute(String latlog){
            if(inputStream==null) {
                Toast.makeText(getApplicationContext(), "Didn't Work", Toast.LENGTH_SHORT).show();
            } else {
                textView.setText(latlog);
            }
        }
    }

getValue(String,Element)

private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }

1 个答案:

答案 0 :(得分:1)

似乎问题不在您的源代码中,而在于访问服务器。可能是URL错误(URL中的拼写错误) - 因此在调用之前检查link变量值

URL url = new URL(link);

可能缺少某些参数。并尝试分析响应代码:

int responseCode = htc.getResponseCode(); 
if (responseCode == HttpURLConnection.HTTP_OK) { 
    inputStream = htc.getInputStream();
    ... 
}

可能是HttpURLConnection should be configured like htc.setRequestMethod(&#34; GET&#34;);`或者类似的东西:HTTP身份验证,代理,Cookie等(参见Official Documentation)。