【问题标题】: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
【解决方案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();