我試圖從谷歌地理編碼api得到一個XML響應。你可以在瀏覽器中看到下面的鏈接,xml響應工作得很好。然而,我的Document.parse()在它返回一個空文檔,並在打印響應的實體的contentLength時,我得到-1。 我發送的地址的語言是希伯來語,但這似乎不是一個問題,因爲在瀏覽器中,響應返回正常。 任何人都可以瞭解發生了什麼,爲什麼它不按預期工作?java文檔失敗解析xml
String url = "https://maps.googleapis.com/maps/api/geocode/xml?"
+ "address=" + URLEncoder.encode(address, "UTF-8");
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
System.out.println(url);
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request, localContext);
System.out.println(Arrays.toString(response.getAllHeaders()));
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
doc = builder.parse(in);
System.out.println(doc.getTextContent());
return doc;
我的作品是(你可以檢查鏈接的有效性):
https://maps.googleapis.com/maps/api/geocode/xml?address=%D7%94%D7%A2%D7%9C%D7%99%D7%94+%D7%94%D7%A9%D7%A0%D7%99%D7%94+20+%D7%90%D7%96%D7%95%D7%A8
[Content-Type: application/xml; charset=UTF-8, Date: Mon, 03 Nov 2014 19:20:50 GMT, Expires: Tue, 04 Nov 2014 19:20:50 GMT, Cache-Control: public, max-age=86400, Vary: Accept-Language, Access-Control-Allow-Origin: *, Server: mafe, X-XSS-Protection: 1; mode=block, X-Frame-Options: SAMEORIGIN, Alternate-Protocol: 443:quic,p=0.01, Transfer-Encoding: chunked]
null
好的想法,但仍爲空 – user2717954 2014-11-03 19:44:43
@ user2717954嘗試'doc.getDocumentElement()'。該文件當然不是空的,否則你會得到'NullPointerException'。 – RealSkeptic 2014-11-03 20:09:27