XML文件的HTTP请求

我正在尝试对Android上的程序使用Flurry Analytics,但无法从服务器获取xml文件本身。

我正在接近,因为在Log Cat System.out标记中由于某种原因我可以得到一半,它说“ XML传递异常=

java.net.MalformedURLException:找不到协议:?xml版本= 1.0编码=“ UTF

-8“等…直到大约完成我的xml代码的一半。不确定我做错了什么,我发送的HTTP get与标头请求接受应用程序/

xml,并且它无法正常工作。任何帮助感激不尽!

try {

//HttpResponse response = client.execute(post);

//HttpEntity r_entity = response.getEntity();

//String xmlString = EntityUtils.toString(r_entity);

HttpClient client = new DefaultHttpClient();

String URL = "http://api.flurry.com/eventMetrics/Event?apiAccessCode=????&apiKey=??????&startDate=2011-2-28&endDate=2011-3-1&eventName=Tip%20Calculated";

HttpGet get = new HttpGet(URL);

get.addHeader("Accept", "application/xml");

get.addHeader("Content-Type", "application/xml");

HttpResponse responsePost = client.execute(get);

HttpEntity resEntity = responsePost.getEntity();

if (resEntity != null)

{

System.out.println("Not null!");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

String responseXml = EntityUtils.toString(responsePost.getEntity());

Document doc = db.parse(responseXml);

doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("eventMetrics");

for (int i = 0; i < nodeList.getLength(); i++)

{

Node node = nodeList.item(i);

Element fstElmnt = (Element) node;

NodeList nameList = fstElmnt.getElementsByTagName("day");

Element dayElement = (Element) nameList.item(0);

nameList = dayElement.getChildNodes();

countString = dayElement.getAttribute("totalCount");

System.out.println(countString);

count = Integer.parseInt(countString);

System.out.println(count);

count += count;

}

}

} catch (Exception e) {

System.out.println("XML Passing Exception = " + e);

}

回答:

采用字符串的parse方法用于URL格式。您需要在解析字符串之前将其包装在StringReader中。如果可以将XML作为InputStream并进行解析,则更好,例如:

String uri =

"http://api.flurry.com/eventMetrics/Event?apiAccessCode=?????&apiKey=??????&startDate=2011-2-28&endDate=2011-3-1&eventName=Tip%20Calculated";

URL url = new URL(uri);

HttpURLConnection connection =

(HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setRequestProperty("Accept", "application/xml");

InputStream xml = connection.getInputStream();

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(xml);

以上是 XML文件的HTTP请求 的全部内容, 来源链接: utcz.com/qa/431345.html

回到顶部