【问题标题】:Receiving XML from HTTP Post从 HTTP Post 接收 XML
【发布时间】:2012-10-14 02:26:08
【问题描述】:

所以我有以下代码:

    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>

谁能帮帮我,不胜感激!

【问题讨论】:

  • 您永远不应该使用 Reader 读取 xml(或将其转换为字符串)。您应该使用 InputStream 并将 xml 数据视为字节,以免意外破坏字符编码。处理响应也是如此。

标签: java xml apache restful-url


【解决方案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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多