简体   繁体   中英

java Document fails parsing xml

I'm trying to get an xml response from google geocoding api. you can see by going in the browser to the link below that the xml response is working just fine. however my Document.parse() on it returns a null doc and when printing the contentLength of the entity of the response I get -1. The language of the address I send is hebrew but that doesn't seem to be a matter since in the browser the response returns just fine. Can anyone understand whats going on and why it doesn't work as intended?

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;

my prints are (you can check the link for validity):

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

The good thing is that your doc seems to be not null. Try getFirstChild or similar. GetTextContent will fail because the root element very likely will have no text in it as a value.

ok just to answer my own question

i ended up using

EntityUtils.toString(response.getEntity())

and changing the respone type to json, tho I still cant understand why didn't the document.parse() work well since with the above line and still requesting for xml it returned the correct string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM