Jersey REST Client: How to add XML file to the body of POST request?

守給你的承諾、 提交于 2019-12-20 02:29:32

问题


My code so far:

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

I want to send contents of filename.xml with POST method but I have no idea how to add them to the body of request. I need help as in the net I was only able to find how to add Form args.

Thanks in advance.


回答1:


You can always use the java.net APIs in Java SE:

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();



回答2:


Have a look at the Jersey API for WebResource. It gives you a post method that accepts data.



来源:https://stackoverflow.com/questions/6665769/jersey-rest-client-how-to-add-xml-file-to-the-body-of-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!