我想从Android中使用HTTP获取方法从URL获取XML文件。当我在浏览器中输入网址时,我得到了XML文件。但是,当我尝试在Android中使用HttpURLConnection时,输入流始终为空。我试图找出问题,但徒劳无功。我想了解一些问题。
这里是我的代码:
XML文件在Android中从URL获取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(字符串,元)
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
XML是一种古老的方式,为什么不切换到JSON?简单而好用 –
为此,我需要知道如何使用_python-cgi-script_发送_json_对象。你能指出我一个体面的教程如何做到这一点?这将是非常有帮助的。 @teckwei – dannyBoy
嗯..我使用PHP的服务器端。 0 python知识我敢打赌,你可以谷歌它。 –