How to get response as XML Document with Apache Ht

2020-06-18 02:32发布

问题:

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");
 }

回答1:

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();
            }                           
        }