JAVA :: RESTful Web Service to consume a XML file

社会主义新天地 提交于 2019-12-08 03:17:13

问题


Is there any other way that we can send an XML file to a RESTful Web Service other than as a FORMPARAM?

My requirement is to develop a webservice which Consumes a XML file, stores it in my local machine and returns a statement saying that the file was downloaded/saved.


回答1:


Here's the code to post, way easier than SOAP...

// POST the XML string as text/xml  via HTTPS
public static String postRequest(String strRequest, String strURL) throws Exception {
    String responseXML = null;

    try {
        URL url = new URL(strURL);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) connection;

        byte[] requestXML = strRequest.getBytes();

        // Set the appropriate HTTP parameters.
        httpConn.setRequestProperty("Content-Length", String.valueOf(requestXML.length));
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        // Send the String that was read into postByte.
        OutputStream out = httpConn.getOutputStream();
        out.write(requestXML);
        out.close();

        // Read the response and write it to standard out.
        InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        String temp;
        String tempResponse = "";

        //Create a string using response from web services
        while ((temp = br.readLine()) != null)
            tempResponse = tempResponse + temp;
        responseXML = tempResponse;
        br.close();
        isr.close();
    } catch (java.net.MalformedURLException e) {
        System.out.println("Error in postRequest(): Secure Service Required");
    } catch (Exception e) {
        System.out.println("Error in postRequest(): " + e.getMessage());
    }
    return responseXML;
}


来源:https://stackoverflow.com/questions/7552900/java-restful-web-service-to-consume-a-xml-file

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