Android, sending XML via HTTP POST (SOAP)

The question:

I would like to invoke a webservice via Android. I need to POST some XML to a URL via HTTP.
I found this snipped for sending a POST, but i dont know how to include/add the XML data itself.

public void postData() {
         // Create a new HttpClient and Post Header  
         HttpClient httpclient = new DefaultHttpClient();  
         HttpPost httppost = new HttpPost("");

         try {  
             // Add your data  
             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
             nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/soap+xml"));               
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
                 // Where/how to add the XML data?

             // Execute HTTP Post Request  
             HttpResponse response = httpclient.execute(httppost);  

         } catch (ClientProtocolException e) {  
             // TODO Auto-generated catch block  
         } catch (IOException e) {  
             // TODO Auto-generated catch block  

This is the complete POST message that i need to imitate:

POST /a8103e90-f1e3-11dd-bfdb-8b1fcff1a110 HTTP/1.1
Content-Type: application/soap+xml
Content-Length: 602

<?xml version='1.0' encoding='UTF-8' ?>
<s12:Envelope xmlns:s12="" xmlns:wsa="">
  <s12:Body />

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

  1. First, you can create a String template for this SOAP request and substitute user-supplied values at runtime in this template to create a valid request.
  2. Wrap this string in a StringEntity and set its content type as text/xml
  3. Set this entity in the SOAP request.

Something like:

HttpPost httppost = new HttpPost(SERVICE_EPR);          
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);


HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = 
    (BasicHttpResponse) httpclient.execute(httppost);


Method 2

here the alternative to send soap msg.

public String setSoapMsg(String targetURL, String urlParameters){

        URL url;
        HttpURLConnection connection = null;  
        try {
          //Create connection
          url = new URL(targetURL);

         // for not trusted site (https)
         // _FakeX509TrustManager.allowAllSSL();
         // System.setProperty("","all");

          connection = (HttpURLConnection)url.openConnection();

          connection.setRequestProperty("SOAPAction", "**** SOAP ACTION VALUE HERE ****");

          connection.setUseCaches (false);

          //Send request
          DataOutputStream wr = new DataOutputStream (
                       connection.getOutputStream ());
          wr.writeBytes (urlParameters);
          wr.flush ();
          wr.close ();

          //Get Response    
          InputStream is ;
          Log.i("response", "code="+connection.getResponseCode());
              /* error from server */
              is = connection.getErrorStream();
         // is= connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer(); 
          while((line = rd.readLine()) != null) {
          Log.i("response", ""+response.toString());
          return response.toString();

        } catch (Exception e) {

         Log.e("error https", "", e);
          return null;

        } finally {

          if(connection != null) {

hope it helps. if anyone wonder allowAllSSL() method, google it :).

Method 3

So if you use:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

It is still rest, but if you use:

StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);

It is soap???

Method 4

Example sending XML to WS via http POST.

DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://foo/service1.asmx/GetUID");     

        //XML example to send via Web Service.
        StringBuilder sb = new StringBuilder();

        httppost.addHeader("Accept", "text/xml");
        httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
        nameValuePairs.add(new BasicNameValuePair("myxml", sb.toString());//WS Parameter and    Value           
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);

Method 5

Here’s my code for sending HTML….
You can see the data is the nameValuePairs.add(…)

        HttpClient httpclient = new DefaultHttpClient();
        // Your URL
        HttpPost httppost = new HttpPost("");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            // Your DATA
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata","AndDev is Cool!"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response;
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block

Method 6

I had to send some XML via HTTP Post on Android too.

String xml = "xml-block";
StringEntity se = new StringEntity(xml,"UTF-8");
HttpPost postRequest = new HttpPost("http://some.url");

Hope it works!

Method 7

here, the code snippets of code, that I am using for posting xml in SOAP services and in return getting Inputstream from web.

 private InputStream call(String soapAction, String xml) throws IOException {

    byte[] requestData = xml.getBytes("UTF-8");
    URL url = new URL(URL);

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    // connection.setRequestProperty("Accept-Encoding","gzip,deflate");
    connection.setRequestProperty("Content-Type", "text/xml; UTF-8");
    connection.setRequestProperty("SOAPAction", soapAction);
    connection.setRequestProperty("User-Agent", "android");
            "base_urlforwebservices like -");
    // connection
    // .setRequestProperty("Content-Length", "" + requestData.length);

    os = connection.getOutputStream();
    os.write(requestData, 0, requestData.length);
    is = connection.getInputStream();
    return is; // inputStream

Here xml: is the built xml request used to call services.

Have fun;

Method 8

Another way of doing it is by using Apache Call. Api URL, Action URI and API Body needs to be provided

InputStream input = new ByteArrayInputStream(apiBody.getBytes());
Service service = new Service();
Call call = (Call) service.createCall();
SOAPEnvelope soapEnvelope = new SOAPEnvelope(input);

call.setTargetEndpointAddress(new URL(apiUrl));

soapEnvelope = call.invoke(soapEnvelope);
return soapEnvelope.toString();

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment