如何使用Apache Httpclient api以XML文档的形式获得响应?

时间:2010-11-18 15:28:56

标签: xml document response httpclient

我可以收到回复。如何在XML文档中获取响应?我需要使用外部XML解析器吗?谢谢你的帮助

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 个答案:

答案 0 :(得分:17)

我得到了我的回答,在这里发布,因为人们有同样的问题

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