在java中的httppost之后处理响应

时间:2012-07-25 19:01:41

标签: java httpclient

我正在使用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

感谢。

1 个答案:

答案 0 :(得分:1)

标准Java DOM API:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(in);

最后一行至关重要。

SAX API

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(in, yourCustomCallback);

JAXB

假设您有合适的模型:

JAXBContext context = JAXBContext.newInstance(Response.class);
Response response = (Response)context.createUnmarshaller().unmarshal(in);