[java] Sending HTTP Post request with SOAP action using org.apache.http

I'm trying to write a hard-coded HTTP Post request with SOAP action, using the org.apache.http api. My problem is I didn't find a way to add a request body (in my case - SOAP action). I'll be glad for some guidance.

import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.RequestWrapper;
import org.apache.http.protocol.HTTP;

public class HTTPRequest
{
    @SuppressWarnings("unused")
    public HTTPRequest()
    {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String body="DataDataData";
            String bodyLength=new Integer(body.length()).toString();
            System.out.println(bodyLength);
//          StringEntity stringEntity=new StringEntity(body);

            URI uri=new URI("SOMEURL?Param1=1234&Param2=abcd");
            HttpPost httpPost = new HttpPost(uri);
            httpPost.addHeader("Test", "Test_Value");

//          httpPost.setEntity(stringEntity);

            StringEntity entity = new StringEntity(body, "text/xml",HTTP.DEFAULT_CONTENT_CHARSET);
            httpPost.setEntity(entity);

            RequestWrapper requestWrapper=new RequestWrapper(httpPost);
            requestWrapper.setMethod("POST");
            requestWrapper.setHeader("LuckyNumber", "77");
            requestWrapper.removeHeaders("Host");
            requestWrapper.setHeader("Host", "GOD_IS_A_DJ");
//          requestWrapper.setHeader("Content-Length",bodyLength);          
            HttpResponse response = httpclient.execute(requestWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This question is related to java apache http post httpwebrequest

The answer is


... using org.apache.http api. ...

You need to include SOAPAction as a header in the request. As you have httpPost and requestWrapper handles, there are three ways adding the header.

 1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
 2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
 3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );

Only difference is that addHeader allows multiple values with same header name and setHeader allows unique header names only. setHeader(... over writes first header with the same name.

You can go with any of these on your requirement.


This is a full working example :

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public void callWebService(String soapAction, String soapEnvBody)  throws IOException {
    // Create a StringEntity for the SOAP XML.
    String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
    StringEntity stringEntity = new StringEntity(body, "UTF-8");
    stringEntity.setChunked(true);

    // Request parameters and other properties.
    HttpPost httpPost = new HttpPost("http://example.com?soapservice");
    httpPost.setEntity(stringEntity);
    httpPost.addHeader("Accept", "text/xml");
    httpPost.addHeader("SOAPAction", soapAction);

    // Execute and get the response.
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    String strResponse = null;
    if (entity != null) {
        strResponse = EntityUtils.toString(entity);
    }
}

The simplest way to identify what needs to be set on the soap action when invoking WCF service through a java client would to load the wsdl, go to the operation name matching the service. From there pick up the action URI and set it in the soap action header. You are done.

eg: from wsdl

<wsdl:operation name="MyOperation">
  <wsdl:input wsaw:Action="http://tempuri.org/IMyService/MyOperation" message="tns:IMyService_MyOperation_InputMessage" />
  <wsdl:output wsaw:Action="http://tempuri.org/IMyService/MyServiceResponse" message="tns:IMyService_MyOperation_OutputMessage" />

Now in the java code we should set the soap action as the Action URI.

//The rest of the httpPost object properties have not been shown for brevity
string actionURI='http://tempuri.org/IMyService/MyOperation';
httpPost.setHeader( "SOAPAction", actionURI);

Here is the example i have tried and it is working for me:

Create the XML file SoapRequestFile.xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

And here the code in java:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }

It was giving 415 Http response Code as error,

So I added

httppost.addHeader("Content-Type", "text/xml; charset=utf-8");

Everything alright now, Http: 200


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to apache

Enable PHP Apache2 Switch php versions on commandline ubuntu 16.04 Laravel: PDOException: could not find driver How to deploy a React App on Apache web server Apache POI error loading XSSFWorkbook class How to enable directory listing in apache web server Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to enable php7 module in apache? java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request