【问题标题】:Jersey REST Client: How to add XML file to the body of POST request?Jersey REST Client:如何将 XML 文件添加到 POST 请求的正文中?
【发布时间】:2011-07-12 14:26:13
【问题描述】:

到目前为止我的代码:

FileReader fileReader = new FileReader("filename.xml");
Client c = Client.create();
WebResource webResource = c.resource("http://localhost:8080/api/resource");
webResource.type("application/xml");

我想用POST 方法发送filename.xml 的内容,但我不知道如何将它们添加到请求正文中。我需要帮助,因为在网上我只能找到如何添加 Form args。

提前致谢。

【问题讨论】:

    标签: java xml web-services rest jersey


    【解决方案1】:

    看看Jersey API for WebResource。它为您提供了一个接受数据的post 方法。

    【讨论】:

      【解决方案2】:

      您始终可以在 Java SE 中使用 java.net API:

      URL url = new URL("http://localhost:8080/api/resource");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setInstanceFollowRedirects(false);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "application/xml");
      
      OutputStream os = connection.getOutputStream();
      
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      FileReader fileReader = new FileReader("filename.xml");
      StreamSource source = new StreamSource(fileReader);
      StreamResult result = new StreamResult(os);
      transformer.transform(source, result);
      
      os.flush();
      connection.getResponseCode();
      connection.disconnect();
      

      【讨论】:

        猜你喜欢
        • 2019-02-09
        • 2023-03-26
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 2021-04-06
        相关资源
        最近更新 更多