Jersey REST Client:如何将XML文件添加到POST请求的主体中?

时间:2011-07-12 14:26:14

标签: java xml web-services rest jersey

到目前为止我的代码:

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

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

提前致谢。

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

您始终可以在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();