我正在使用httpclient在java中发布xml。我也期待一个xml作为回应。 如何将响应解析为xml?
这是我到目前为止所拥有的
HttpClient cliet = HttpClientFactory.getClient("mhurl.com");
...
PostMethod post;
post.setRquestEntity(new StringRequestEntity(myxml_in_string,"xml",...);
...
int result = client.executeMethod(post);
InputStream in = post.getRespoinseBodyAsStream();
?? //Not sure how to handle the response from here
感谢。
答案 0 :(得分:1)
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(in);
最后一行至关重要。
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(in, yourCustomCallback);
假设您有合适的模型:
JAXBContext context = JAXBContext.newInstance(Response.class);
Response response = (Response)context.createUnmarshaller().unmarshal(in);