从HTTP Post接收XML

时间:2012-10-14 02:26:09

标签: java xml apache restful-url

所以我有以下代码:

    public void SendToApplication(HttpServletRequest request) throws IOException, TransformerException {

        BufferedReader br = new BufferedReader(new FileReader(new File("CreatePoll.xml")));
        String line;
        StringBuilder sb = new StringBuilder();

        while((line=br.readLine())!= null) sb.append(line.trim());

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://localhost:8080/cs9322.simple.rest.doodle/rest/polls/comment");
        StringEntity input = new StringEntity(sb.toString());
        input.setContentType("text/xml");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        HttpEntity entity = response.getEntity();

    }

其中读取XML文件(CreatePoll.xml),

<Comment xmlns:xs="http://localhost:8080/cs9322.simple.rest.doodle/CommentSchema">
  <Poll_ID>2</Poll_ID>
  <Name>Bob</Name>
  <Text>testing junk</Text>
  <Timestamp>2012-10-14T12:37:04</Timestamp>
</Comment>

并将其发布到Web服务,我现在遇到的问题是尝试在发送后从Web服务接收XML响应。我打算收到的XML是:

<comment>
    <address>
    </address>
</comment>

有人可以帮助我,非常感谢!

1 个答案:

答案 0 :(得分:1)

如果您使用Apache Commons IO,则可以使用IOUtils类从HttpEntity读取输入流。使用twitter Rest API的示例:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://search.twitter.com/search.atom?q=elkstein&count=5");
HttpResponse response = httpClient.execute(postRequest);

HttpEntity entity = response.getEntity();
String body = IOUtils.toString(entity.getContent(), "UTF-8");
相关问题