Tuesday, 12 January 2016

How to pass xml data over HTTP post to an endpoint

A third party service can be invoked from any application using the HTTP protocols that they expose. The data that needs to be sent as part of the request, can be appended to the request through the outputstream. There are various types of data that can be sent over the HTTP Post method.

Below are the steps involved in sending xml data over HTTP Post.

      Setup the initial connection:
URL  serverAddress = new URL(endpoint_url);
            HttpURLConnection connection = null;
            connection = (HttpURLConnection) serverAddress.openConnection();

      endpoint_url – Extrenal URL to which the connection to be made.           
      
      Add headers to the request:

     The http method type and the content type can be set in the request header using the below code.
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept-charset", "UTF-8");
            connection.setRequestProperty("content-type", "text/xml; charset=utf-8");

      Include data in the request:
       
        Set whether the request has any output data and expects back any input data as part of the connection response.
             connection.setDoInput(true);
            connection.setDoOutput(true);
                
       Add the contents to be sent as part of the HTTP Post request. Make sure that the charset is added as required by the content.
wr = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            System.out.println(xmlstr);
            output.writeBytes(xmlstr);
            output.flush();
            output.close();

      Connect and process the input sent as part of response:

        The connection response will have the response code and message based on which the status of the call can be evaluated. A response code 200 will be sent on successful processing of the request at the endpoint URL. The input sent from the URL can be obtained from the inputstream and can be parsed and used for further processing.
             connection.connect();
            int rc = connection.getResponseCode();
            System.out.println(rc);
            System.out.println(connection.getResponseMessage());
            rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                 sb.append(line);
            }
            String resultStr = sb.toString();
            System.out.println(resultStr);

Note:  A 400 response code will be sent back when there is a malformation in the request data. Make sure that the content type is added as part of the request header in case of xml data. The xml data should be in correct format and the elements should be as expected by third party application

No comments:

Post a Comment