gpt4 book ai didi

java - 对 XML 文件的 HTTP 请求

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:32 26 4
gpt4 key购买 nike

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

我越来越接近了,因为在 Log Cat System.out 标记中,出于某种原因我可以得到它的一半,它说“XML 传递异常 = java.net.MalformedURLException:找不到协议(protocol):?xml 版本 = 1.0 编码="UTF-8"等等...直到我的 xml 代码大约一半。不确定我做错了什么,我正在发送一个 HTTP get 请求接受 application/xml 的 header 并且它无法正常工作. 任何帮助表示赞赏!

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 格式。在解析之前,您需要将 String 包装在 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);

关于java - 对 XML 文件的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5162063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com