1

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.

Harsha
  • 51
  • 2
  • 2
  • 4
  • RESTful wid Jersey is the actual requirement! – Harsha Sep 26 '11 at 14:18
  • Check out http://stackoverflow.com/questions/1725315/how-to-get-full-rest-request-body-using-jersey/1773308#1773308 -- it's as easy as just *not* having a `@FormParam` annotation: `@POST public void store(String xml) { ...` – Philipp Reichart Sep 26 '11 at 15:07
  • To be RESTful, don't return anything from a POST unless things break (i.e. the default "200 OK" is enough). Jersey will probably come up with a nice error message by itself anyway. – Philipp Reichart Sep 26 '11 at 15:09

1 Answers1

2

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;
}
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
William Walseth
  • 2,803
  • 1
  • 23
  • 25