How to get response as XML Document with Apache Httpclient api?
21,066
I got my answer, post here for people have the same question
DefaultHttpClient client = new DefaultHttpClient();
String getUrl = "http://myurl.com";
HttpUriRequest getRequest = new HttpGet(getUrl);
getRequest.setHeader("User-Agent", "xxxx");
HttpResponse response = client.execute(getRequest);
int statusCode = response.getStatusLine().getStatusCode();
log.info("statusCode=" + statusCode);
Document doc = null;
if (statusCode == 200 ){
HttpEntity entity = response.getEntity();
//String content = EntityUtils.toString(entity);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(entity.getContent());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
Author by
androidkc
Updated on July 05, 2022Comments
-
androidkc almost 2 years
I can receive the response. How can I get the response in a XML document? do I need to use an external XML parser? thanks for any helps
DefaultHttpClient client = new DefaultHttpClient(); String getUrl = "http://myurl.com"; HttpUriRequest getRequest = new HttpGet(getUrl); getRequest.setHeader("User-Agent", "xxxx"); HttpResponse response = client.execute(getRequest); int statusCode = response.getStatusLine().getStatusCode(); log.info("statusCode=" + statusCode); if (statusCode == 200 ){ HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); log.info("\n" + content); }else { log.warn("failed to response"); }
-
2cupsOfTech about 10 yearsOn Android it is recommended to use the XmlPullParser. It has a relatively simple API compared to SAX and DOM and is fast and requires less memory then the DOM API. developer.android.com/training/basics/network-ops/xml.html
-
Menuka Ishan over 8 yearsIDE warns DefaultHttpClient is deprecated. What is the alternative for it? HttpClient?
-
douglas about 8 yearsMenuka Ishan: the alternative is HttpClient client = HttpClientBuilder.create().build();