【问题标题】:How to sent XML file endpoint url in Restful web service如何在 Restful Web 服务中发送 XML 文件端点 url
【发布时间】:2015-10-01 09:54:32
【问题描述】:
我需要将请求 XML 文件作为多部分表单数据发送到 {url}。这在 Restful 网络服务中是如何实现的。在我在那里使用之前,
RequestDispatcher rd = request.getRequestDispatcher("/file/message.jsp");
rd.forward(request, response);
但这不是在特定的{url}中发送的,如何发送?
【问题讨论】:
标签:
java
tomcat
request
restful-architecture
endpoint
【解决方案1】:
您可以使用Jersey Rest Client 以post request 发送您的XML 消息。
try {
Client client = Client.create();
WebResource webResource = client.resource(http://<your URI>);
// POST method
ClientResponse response = webResource.accept("multipart/form-data").type("multipart/form-data").post(ClientResponse.class, "<your XML message>");
// check response status code
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
// display response
String output = response.getEntity(String.class);
System.out.println("Output from Server .... ");
System.out.println(output + "\n");
} catch (Exception e) {
e.printStackTrace();
}
对于 Jersey 客户,您可以在此处找到文档:
Jersey REST Client
WebResource
【解决方案2】:
如果你能做到(取决于你的上下文),使用 JAX-RS 客户端是一种解决方案。
Apache CXF 示例:
InputStream inputStream = getClass().getResourceAsStream("/file/message.jsp");
WebClient client = WebClient.create("http://myURL");
client.type("multipart/form-data");
ContentDisposition cd = new ContentDisposition("attachment;filename=message.jsp");
Attachment att = new Attachment("root", inputStream, cd);
client.post(new MultipartBody(att));
【解决方案3】:
我认为 Web 服务不是您的最佳选择
您可以尝试使用原生流,然后您可以随意编写标题和正文这里是解释我的观点的示例代码
Socket socket=new new socket(InetAddress.getByName("stackoverflow.com"), 80);
// just the host and the port
Writer out = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
out.write("POST http://" + HOST + ":" + port+ "/ HTTP/1.1\r\n");//here u can insert your end point or the page accepts the xml msg
out.write("Host: " + HOST + "/ \r\n");
out.write("Content-type: application/xml,text/xml\r\n");// Accept
out.write("Content-length: " + req.length() + "\r\n");
out.write("Accept:application/xml,text/xml\r\n");
out.write("\r\n");
// req the Request Body or the xml file to be sent
out.write(req);//
out.flush();`