【问题标题】:Sending a XML file via POST to a RESTful service in Java通过 POST 将 XML 文件发送到 Java 中的 RESTful 服务
【发布时间】:2012-10-04 09:14:56
【问题描述】:

我需要使用 POST 将 XML 文件发送到 Web 服务。我有一个客户端应用程序,它创建一个 XML 文件,该文件存储发送到 Web 应用程序所需的所有信息,但我不知道如何发送它。

我的 XML 如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Comment>
  <Poll_ID>2</Poll_ID>
  <Name>wpoon</Name>
  <Text>asdasdas</Text>
  <Timestamp>2012-10-14T10:30:25</Timestamp>
</Comment>

我将发送到的 RESTful 服务具有 URL:

http://localhost:8080/TESTINGrestful/rest/polls/comment

谁能告诉我如何做到这一点,任何帮助将不胜感激。

【问题讨论】:

    标签: java xml rest


    【解决方案1】:

    与以前的方法类似,但使用 HttpClientBuilder 而不是已弃用的 DefaultHttpClient。此示例还使用 contentType Json

    HttpPost postRequest = new HttpPost( "http://localhost:8080/service_url" );
    
    StringEntity input = new StringEntity("{\"jsonExample\": \"12345\"}");
    input.setContentType("application/json");
    postRequest.setEntity(input);
    
    HttpResponse response = HttpClientBuilder.create().build().execute(postRequest);
    
    String json = EntityUtils.toString(response.getEntity());
    

    【讨论】:

      【解决方案2】:

      有一个很好的例子 here 来自 Apache HttpClient

      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost postRequest = new HttpPost("http://localhost:8080/TESTINGrestful/rest/polls/comment");
      StringEntity input = new StringEntity("<Comment>...</Comment>");
      input.setContentType("text/xml");
      postRequest.setEntity(input);
      HttpResponse response = httpClient.execute(postRequest);
      

      【讨论】:

        猜你喜欢
        • 2014-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        相关资源
        最近更新 更多