I need to send the request XML file to {url} as multipart form data. How this do in Restful web service. Before I use in there in,
RequestDispatcher rd = request.getRequestDispatcher("/file/message.jsp");
rd.forward(request, response);
But this isn't sent in specific {url}, How to sent it?
You can use the Jersey Rest Client
to send your XML message as post request
.
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();
}
For Jersey Client you can find documentation here:
Jersey REST Client
WebResource
If you can do it (depends on your context), using a JAX-RS client is a solution.
Example with 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));
I don't think web service is best choice for you
you can try native stream and then you can write the header and the body as you like here is sample code to explain my point
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();`