How to sent XML file endpoint url in Restful web service

筅森魡賤 提交于 2019-12-12 03:18:51

问题


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?


回答1:


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




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/32884587/how-to-sent-xml-file-endpoint-url-in-restful-web-service

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