559

I am having a lot of trouble finding good information on how to call a standard SOAP/WSDL web service with Android. All I've been able to find are either very convoluted documents and references to "kSoap2" and then some bit about parsing it all manually with SAX. OK, that's fine, but it's 2008, so I figured there should be some good library for calling standard web services.

The web service is just basically one created in NetBeans. I would like to have IDE support for generating the plumbing classes. I just need the easiest/most-elegant way to contact a WSDL based web service from an Android-based phone.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
BobbyShaftoe
  • 27,660
  • 5
  • 50
  • 71
  • If somebody previously familiar with MS VS, using Mono for Android will solve many problems with data services and web services, everything is simple and fast development. Also who is not familiar with C# (code very similar to Java), all library has the same methods, some functions replaced on properties, so names almost the same and who wrote before on Java for android can very easy using their experience to write c# code. – Eugene Bosikov Feb 14 '13 at 17:42
  • Here is very good link on using SOAP in android: [How to Call Web Service in Android Using SOAP](http://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/) – Jainendra Jan 16 '13 at 17:52
  • Have a look at the below Link it has a detailed Eaxample on accessing a webservice in Android Using Ksoap2 [Accessing a Webservice from Android](http://codeoncloud.blogspot.com/2012/04/android-web-service-access-tutorial.html) – Fred Ondieki Dec 31 '13 at 09:54
  • I believe this is possible with Xamarin/C# using .Net Core. see https://blogs.msdn.microsoft.com/webdev/2016/05/25/announcing-wcf-connected-service-for-net-core-rc2-and-asp-net-core-rc2/ – Vahid Amiri Jun 18 '16 at 18:13
  • This [tool](https://spring.io/guides/gs/consuming-web-service/) by Spring looks promising. – Louis Aug 23 '17 at 12:24

26 Answers26

249

Android does not provide any sort of SOAP library. You can either write your own, or use something like kSOAP 2. As you note, others have been able to compile and use kSOAP2 in their own projects, but I haven't had to.

Google has shown, to date, little interest in adding a SOAP library to Android. My suspicion for this is that they'd rather support the current trends in Web Services toward REST-based services, and using JSON as a data encapsulation format. Or, using XMPP for messaging. But that is just conjecture.

XML-based web services are a slightly non-trivial task on Android at this time. Not knowing NetBeans, I can't speak to the tools available there, but I agree that a better library should be available. It is possible that the XmlPullParser will save you from using SAX, but I don't know much about that.

foxxtrot
  • 10,664
  • 4
  • 25
  • 27
  • 7
    Yeah, I think I will have to build a REST proxy. It seems pretty strange that Google has no interest in providing SOAP support. I tried the kSoap method, it's really not even a serious alternative. It is, at best, an ugly had that requires much scouring of newsgroups. – BobbyShaftoe Nov 22 '08 at 02:27
  • 19
    The reason is probably that SOAP is very verbose and doesn't serve the constraints of mobile computing well. – Neil Nov 26 '09 at 21:46
  • 93
    This answer would be improved if someone could **suggest the best alternative** to calling web services with an Android App. Once people find this question and read it, that's what most of them will be looking for. – MGOwen Dec 22 '09 at 03:55
  • 4
    SOAP processing is also memory and processor intensive compared to a more concise format like JSON. – Jeremy Edwards Mar 02 '10 at 06:15
  • 3
    @MGOwen The best alternative I can see is a proxy. Implement a REST-ful interface that proxies the SOAP envelopes through WSDL2Java. –  Jul 15 '11 at 17:57
  • 1
    @MGOwen please check my answer, currently it is best and only alternative as customers get support for the license fees paid. – Akash Kava Sep 09 '11 at 09:09
  • 2
    KSoap library can't manage huge request or response. All data is loaded on memory, so could happen that App crashes and OutOfMemory exception occurs. – kinghomer Oct 04 '12 at 13:26
99

org.apache.http.impl.client.DefaultHttpClient comes in the Android SDK by default. That'll get you connected to the WSDL.

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.example.com/" + URL);
HttpResponse response = httpClient.execute(httpGet, localContext);
Sarah Vessels
  • 27,994
  • 29
  • 147
  • 217
Neil
  • 2,176
  • 1
  • 20
  • 26
  • 5
    Yeah, this would be the route where I would have to manually parse everything, I wouldn't get an object oriented approach. – BobbyShaftoe Jan 08 '09 at 23:59
  • 93
    You mean you wouldn't get a free lunch. Manual parsing doesn't have anything to do with OO. I could parse everything on paper with my most advanced tool being an HB1 pencil and it would still be OO. – Neil Jan 18 '09 at 21:01
  • 8
    I believe by OO the author meant Java-XML binding. What would be your next step in this approach to parse the response? And if it has hundreds of elements, organized in a tree structure? – rustyx Jul 07 '11 at 14:26
  • 12
    BTW, I would expect at least an HTTP POST not a GET if you want to have any luck with SOAP. Also, where's the Accept and SOAPAction headers? If you really want to go commando it will take much more than these 4 lines to consume a SOAP service. – rustyx Jul 07 '11 at 14:31
  • 1
    If I had my druthers I wouldn't use SOAP for a web serivce to start with. I'd go RESTful with XML or better yet JSON. You are writing a client on a mobile device. Do you really want to use the device itself to parse WSDL, automatically create the supporting classes and then the proxy itself before even making its first web service call? How often are you going to do this? What's the application exactly? O.o – Neil Jul 07 '11 at 19:11
  • 6
    @NeilD: What if you were forced by circumstances to use SOAP, e.g. the webserver uses SOAP and you have not control over this? – Bjarke Freund-Hansen Feb 02 '12 at 14:33
  • @bjarkef: kSOAP 2 seems to be a popular choice, as per the answer above. Although there's nothing innately unmanageable about consuming SOAP without it, it's just more work. You could also write a proxy server and decouple the SOAP web service in question and your mobile client, but that may turn out to be a much larger task than simply adopting kSOAP or some other similar library. – Neil Feb 06 '12 at 20:02
  • Yeah, this is not really answering the OP's question. Turns out to be useful to me (in my case, I don't even really care that much about the SOAP response, I just need to make sure the service is alive; so even though it's disappointing there's no built in SOAP library, a refresher in how to do a basic POST in Android is handy) but it's not really answering *this* question. – user435779 Dec 06 '13 at 19:34
  • Is there any way to send XML headers without using ksoap? – Sneha Sarkar Jun 13 '18 at 13:13
60

It's true that due to it's overhead SOAP is not the best choice for data exchange with mobile devices. However, you might find yourself in situation in which you do not control the format of server output.

So, if you have to stick with SOAP, there is a kSOAP2 library patched for Android here:
http://code.google.com/p/ksoap2-android/

Viktor Brešan
  • 4,460
  • 5
  • 29
  • 30
31

To call a web service from a mobile device (especially on an Android phone), I have used a very simple way to do it. I have not used any web service client API in attempt to call the web service. My approach is as follows to make a call.

  1. Create a simple HTTP connection by using the Java standard API HttpURLConnection.
  2. Form a SOAP request. (You can make help of SOAPUI to make a SOAP request.)
  3. Set doOutPut flag as true.
  4. Set HTTP header values like content-length, Content type, and User-agent. Do not forget to set Content-length value as it is a mandatory.
  5. Write entire the SOAP request to the output stream.
  6. Call the method to make a connection and receive the response (In my case I used getResonseCode).
  7. If your received response code as
    1. It means you are succeeded to call web service.
  8. Now take an input stream on the same HTTP connection and receive the string object. This string object is a SOAP response.
  9. If the response code is other than 200 then take a ErrorInput stream on same HTTPobject and receive the error if any.
  10. Parse the received response using SAXParser (in my case) or DOMParaser or any other parsing mechanism.

I have implemented this procedure for the Android phone, and it is successfully running. I am able to parse the response even if it is more than 700 KB.

Priyanjan
  • 329
  • 3
  • 5
30

SOAP is an ill-suited technology for use on Android (or mobile devices in general) because of the processing/parsing overhead that's required. A REST services is a lighter weight solution and that's what I would suggest. Android comes with a SAX parser, and it's fairly trivial to use. If you are absolutely required to handle/parse SOAP on a mobile device then I feel sorry for you, the best advice I can offer is just not to use SOAP.

jasonhudgins
  • 2,737
  • 1
  • 23
  • 20
24

DON'T FORGET TO ADD ksoap2.jar in your project and also add the INTERNET permission in AndroidManifest file

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class WebserviceActivity extends Activity {

    private static final String NAMESPACE = "https://api.authorize.net/soap/v1/";
    private static final String URL ="https://apitest.authorize.net/soap/v1/Service.asmx?wsdl"; 
    private static final String SOAP_ACTION = "https://api.authorize.net/soap/v1/AuthenticateTest";
    private static final String METHOD_NAME = "AuthenticateTest";
    private TextView lblResult;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lblResult = (TextView) findViewById(R.id.tv);

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        request.addProperty("name","44vmMAYrhjfhj66fhJN");
        request.addProperty("transactionKey","9MDQ7fghjghjh53H48k7e7n");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);

            //SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            // SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;


            lblResult.setText(resultsRequestSOAP.toString());
            System.out.println("Response::"+resultsRequestSOAP.toString());


        } catch (Exception e) {
            System.out.println("Error"+e);
        }

    }
}
diegueus9
  • 20,833
  • 15
  • 58
  • 73
Amit kumar
  • 1,585
  • 1
  • 16
  • 27
  • HttpTransportSE where can i get this class ?? – Noman Nov 23 '12 at 06:40
  • Hello, i am using your code but i am getting following error, Response::AuthenticateTestResponse{AuthenticateTestResult=anyType{resultCode=Error; messages=anyType{MessagesTypeMessage=anyType{code=E00014; text=Merchant Authentication is required.; }; }; }; } can you help me please? – Hasmukh Jul 10 '13 at 10:56
  • hi Amit i m also amit ..... Can u tell me how response we compare when we got response is successful or not so how and what conditions to check response ...... – Amitsharma Aug 14 '14 at 11:40
  • how to add array in xml of request property? – droidster.me Dec 09 '16 at 06:59
24

About a year ago I was reading this thread trying to figure out how to do SOAP calls on Android - the suggestions to build my own using HttpClient resulted in me building my own SOAP library for Android:

IceSoap

Basically it allows you to build up envelopes to send via a simple Java API, then automatically parses them into objects that you define via XPath... for example:

<Dictionary>
    <Id></Id>
    <Name></Name>
</Dictionary>

Becomes:

@XMLObject("//Dictionary")
public class Dictionary {
    @XMLField("Id")
    private String id;

    @XMLField("Name")
    private String name;
}

I was using it for my own project but I figured it might help some other people so I've spent some time separating it out and documenting it. I'd really love it if some of your poor souls who stumble on this thread while googling "SOAP Android" could give it a go and get some benefit.

ESala
  • 5,973
  • 3
  • 30
  • 50
Alex Gilleran
  • 588
  • 3
  • 12
21

I had my tryst with KSOAP; I chose a rather simpler approach.

Given a WSDL file, create SOAP Request templates for each Request(for e.g.: using SOAP UI) and then substitute the values to be passed in code. POST this data to the service end point using DefaultHttpClient instance and get the response stream. Parse the Response Stream using an XML Pull parser.

Samuh
  • 35,513
  • 26
  • 104
  • 116
18

You can have a look at WSClient++

Akash Kava
  • 37,127
  • 20
  • 114
  • 162
16

I've created a new SOAP client for the Android platform. It is using a JAX-WS generated interface, but it is only a proof-of-concept so far.

If you are interested, please try the example and/or watch the source at AndroidSOAP.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gábor AUTH
  • 456
  • 4
  • 5
  • 1
    I had the pleasure to attend your presentation at JUM XVII. Budapest about this Android stuff. Keep up the good work! – pcjuzer Nov 19 '10 at 09:58
15

If you can, go for JSON. Android comes with the complete org.json package

Yves
  • 151
  • 1
  • 2
14

Call ksoap2 methods. It works very fine.

Set up the details, like

private static String mNAMESPACE=null;
private static String mURL=null;
public static Context context=null;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);

envelope.addMapping(mNAMESPACE, "UserCredentials",new UserCredendtials().getClass());
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(mURL);

and then to get the result do

androidHttpTransport.call(SOAP_ACTION, envelope);
result = (SoapPrimitive)envelope.getResponse();
user370305
  • 103,719
  • 23
  • 157
  • 149
DEVANG SHARMA
  • 2,572
  • 4
  • 30
  • 49
13

I hope Calling a web service from Android helps.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Monte Chan
  • 1,154
  • 4
  • 17
  • 37
11

Few months ago I was working with jax-ws web service in j2ee application, There we were using CXF wsdl2java to generate WS client stub from the WSDL file and with those client stubs we consumed the web services. Few weeks ago, when I was trying to consume the web service in the same way in android platform I couldn't, because the android jar has not all the "jax-ws" supporting classes in it. That time I didn't find any such tool ( if I wasn't failed to google efficiently) to meet my requirement --

  • Get the client stub from the WSDL.
  • And call the Service with some argument (java business request object).
  • Get the Response Business Object.

So, I developed my own Android SOAP Client Generation Tool. Where you have to follow these steps :

  • From WSDL Get WS Client Stub, Put it in your project.
  • Say for Some Service "ComplexOperationService", Instantiate the Service, Get the Endpoint port and call the service method, and get the response from the Web service :

eg:

ComplexOperationService service = new ComplexOperationService( );
ComplexOperation port= service.getComplexOperationPort();    
SomeComplexRequest request = --Get some complex request----;    
SomeComplexResp resp = port.operate( request  );
  • You don't need to care about the service class/req/response classes or any other classes and the method as well, as you know its all are generated from WSDL.
  • And of course you needn't be aware of the soap action/envelop/namespace etc. Just call the method as we, developers do all the time.
Jared Burrows
  • 50,718
  • 22
  • 143
  • 180
Asraful Haque
  • 713
  • 8
  • 11
  • Do you know how to deal with Date? Apache CXF translate it to XMLGregorianCalendar which I am not able to create in Android. – Martin Nuc Apr 13 '13 at 15:45
9

I am sure you could make a little SOAP client with Axis. Axis installation instructions.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
branchgabriel
  • 4,112
  • 4
  • 32
  • 47
  • 2
    That would work only if axis were compatible with Android. It's not (something about javax.* packages in the axis dependencies). – PaulProgrammer Dec 17 '13 at 19:49
8

I think Call SOAP Web Service from Android application will help you a lot.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Srikanth Naidu
  • 757
  • 5
  • 16
  • 27
6

Follow these steps by the method SOAP

From the WSDL file,

  • create SOAP Request templates for each Request.

  • Then substitute the values to be passed in code.

  • POST this data to the service end point using DefaultHttpClient instance.

  • Get the response stream and finally

  • Parse the Response Stream using an XML Pull parser.

Manick
  • 647
  • 2
  • 14
  • 22
6

For me the easiest way is to use good tool to generate all required classes. Personally I use this site:

http://easywsdl.com/

It supports quite complex web services and uses ksoap2.

robocik
  • 609
  • 7
  • 14
6

If you can use JSON, there is a whitepaper, a video and the sample.code in Developing Application Services with PHP Servers and Android Phone Clients.

Daniele Teti
  • 1,703
  • 13
  • 19
5

If you are having problem regarding calling Web Service in android then You can use below code to call the web service and get response. Make sure that your the web service return the response in Data Table Format..This code will help you if you using data from SQL Server database. If you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

void callWebService(){ 

private static final String NAMESPACE = "http://tempuri.org/"; // for wsdl it may be package name i.e http://package_name
private static final String URL = "http://localhost/sample/services/MyService?wsdl";
// you can use IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = "urn:" + METHOD_NAME;

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("parm_name", prm_value);// Parameter for Method
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;// **If your Webservice in .net otherwise remove it**
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);// call the eb service
                                                                                                         // Method
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Next task is to get Response and format that response
    SoapObject obj, obj1, obj2, obj3;
    obj = (SoapObject) envelope.getResponse();
    obj1 = (SoapObject) obj.getProperty("diffgram");
    obj2 = (SoapObject) obj1.getProperty("NewDataSet");

    for (int i = 0; i < obj2.getPropertyCount(); i++) { 
// the method getPropertyCount() and  return the number of rows
            obj3 = (SoapObject) obj2.getProperty(i);
            obj3.getProperty(0).toString();// value of column 1
            obj3.getProperty(1).toString();// value of column 2
            // like that you will get value from each column
        }
    }

If you have any problem regarding this you can write me..

Sachin D
  • 1,362
  • 7
  • 28
  • 42
5

I would suggest checking out a very useful tool that helped me a lot. The guys who take care of that project were very helpful, too. www.wsdl2code.com/

miroslavign
  • 1,912
  • 2
  • 22
  • 26
4

This is a working example of consuming SOAP web services in android.

**Note ::***DON'T FORGET TO ADD ksoap2.jar in your project and also add the INTERNET permission in AndroidManifest file*

public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public final String METHOD_NAME = "FahrenheitToCelsius";
public final String PROPERTY_NAME = "Fahrenheit";
public final String SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
public final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";


private class TestAsynk extends AsyncTask<String, Void, String> {

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        Toast.makeText(getApplicationContext(),
                String.format("%.2f", Float.parseFloat(result)),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(String... params) {
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                METHOD_NAME);
        request.addProperty(PROPERTY_NAME, params[0]);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(
                SOAP_ADDRESS);
        Object response = null;
        try {

            androidHttpTransport.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();
            Log.e("Object response", response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }
}
Kishore Kumar
  • 11,843
  • 26
  • 86
  • 149
Arun
  • 4,214
  • 6
  • 38
  • 54
  • please help me on this issue http://stackoverflow.com/questions/41573829/how-to-send-and-receive-soap-data-from-webservice-to-google-app-engine – Edijae Crusar Jan 10 '17 at 18:41
4

Please download and add SOAP library file with your project File Name : ksoap2-android-assembly-3.4.0-jar-with-dependencies

Clean the application and then start program

Here is the code for SOAP service call

    String SOAP_ACTION = "YOUR_ACTION_NAME";
    String METHOD_NAME = "YOUR_METHOD_NAME";
    String NAMESPACE = "YOUR_NAME_SPACE";
    String URL = "YOUR_URL";
    SoapPrimitive resultString = null;

    try {
        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        addPropertyForSOAP(Request);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        soapEnvelope.dotNet = true;
        soapEnvelope.setOutputSoapObject(Request);

        HttpTransportSE transport = new HttpTransportSE(URL);

        transport.call(SOAP_ACTION, soapEnvelope);
        resultString = (SoapPrimitive) soapEnvelope.getResponse();

        Log.i("SOAP Result", "Result Celsius: " + resultString);
    } catch (Exception ex) {
        Log.e("SOAP Result", "Error: " + ex.getMessage());
    }
    if(resultString != null) {
        return resultString.toString();
    }
    else{
        return "error";
    }

The results may be JSONObject or JSONArray Or String

For your better reference, https://trinitytuts.com/load-data-from-soap-web-service-in-android-application/

Thanks.

lokesh s
  • 111
  • 3
3

You may perform soap call as post over http with certain headers. I solved this question without additional libraries like ksoap2 Here is live code getting orders from soap service

private static HashMap<String,String> mHeaders = new HashMap<>();

static {
    mHeaders.put("Accept-Encoding","gzip,deflate");
    mHeaders.put("Content-Type", "application/soap+xml");
    mHeaders.put("Host", "35.15.85.55:8080");
    mHeaders.put("Connection", "Keep-Alive");
    mHeaders.put("User-Agent","AndroidApp");
    mHeaders.put("Authorization","Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
}public final static InputStream receiveCurrentShipments(String stringUrlShipments)
{
    int status=0;
    String xmlstring= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ser=\"http://35.15.85.55:8080/ServiceTransfer\">\n" +
            "   <soap:Header/>\n" +
            "   <soap:Body>\n" +
            "      <ser:GetAllOrdersOfShipment>\n" +
            "         <ser:CodeOfBranch></ser:CodeOfBranch>\n" +
            "      </ser:GetAllOrdersOfShipment>\n" +
            "   </soap:Body>\n" +
            "</soap:Envelope>";
    StringBuffer chaine = new StringBuffer("");

    HttpURLConnection connection = null;
    try {
        URL url = new URL(stringUrlShipments);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Length", xmlstring.getBytes().length + "");
        connection.setRequestProperty("SOAPAction", "http://35.15.85.55:8080/ServiceTransfer/GetAllOrdersOfShipment");

        for(Map.Entry<String, String> entry : mHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            connection.setRequestProperty(key,value);

        }

        connection.setRequestMethod("POST");
        connection.setDoInput(true);

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(xmlstring.getBytes("UTF-8"));
        outputStream.close();

        connection.connect();
        status = connection.getResponseCode();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        Log.i("HTTP Client", "HTTP status code : " + status);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return inputStream;
}
Lapenkov Vladimir
  • 2,446
  • 2
  • 22
  • 35
  • please help here http://stackoverflow.com/questions/41573829/how-to-send-and-receive-soap-data-from-webservice-to-google-app-engine – Edijae Crusar Jan 10 '17 at 18:35
  • two questions on this: 1. How is this called from main activity? 2. What should be the value of StringUrlShipment that's passed as a parameter? – Tori Feb 22 '17 at 08:55
  • on the above comment, ignore question #1. – Tori Feb 22 '17 at 09:02
  • From main activity you should use AsyncTask to call this code. Inside this AsyncTask class implement doInBackground to launch this code – Lapenkov Vladimir Sep 22 '17 at 08:21
2

To call a SOAP web Service from android , try to use this client

DON'T FORGET TO ADD ksoap2-android.jar in your java build path

public class WsClient {
    private static final String SOAP_ACTION = "somme";
    private static final String OPERATION_NAME = "somme";
    private static final String WSDL_TARGET_NAMESPACE = "http://example.ws";
    private static final String SOAP_ADDRESS = "http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl";

    public String caclculerSomme() {

        String res = null;
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                OPERATION_NAME);
        request.addProperty("a", "5");
        request.addProperty("b", "2");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

        try {
            httpTransport.call(SOAP_ACTION, envelope);
            String result = envelope.getResponse().toString();
            res = result;
            System.out.println("############# resull is :" + result);
        } catch (Exception exception) {
            System.out.println("########### ERRER" + exception.getMessage());
        }

        return res;
    }
}
Nhan Nguyen
  • 410
  • 2
  • 12
Wajdi Hh
  • 745
  • 3
  • 9
  • @ Wajdi hh how to compare response res from giver response result :- success ....."responce =1~Successfull".... so how we compare that result from condition which are from server side ........ – Amitsharma Aug 14 '14 at 11:43
1

Add Soap Libaray(ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar):

public static String Fn_Confirm_CollectMoney_Approval(

        HashMap < String, String > str1,
        HashMap < String, String > str2,
        HashMap < String, String > str3) {

    Object response = null;
    String METHOD_NAME = "CollectMoney";
    String NAMESPACE = "http://xxx/yyy/xxx";
    String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    String SOAP_ACTION = "";

    try {

        SoapObject RequestParent = new SoapObject(NAMESPACE, METHOD_NAME);

        SoapObject Request1 = new SoapObject(NAMESPACE, "req");

        PropertyInfo pi = new PropertyInfo();

        Set mapSet1 = (Set) str1.entrySet();

        Iterator mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            String keyValue = (String) mapEntry.getKey();

            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        mapSet1 = (Set) str3.entrySet();

        mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        SoapObject HeaderRequest = new SoapObject(NAMESPACE, "XXX");

        Set mapSet = (Set) str2.entrySet();

        Iterator mapIterator = mapSet.iterator();

        while (mapIterator.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            HeaderRequest.addProperty(pi);
        }

        Request1.addSoapObject(HeaderRequest);

        RequestParent.addSoapObject(Request1);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER10);

        soapEnvelope.dotNet = false;

        soapEnvelope.setOutputSoapObject(RequestParent);

        HttpTransportSE transport = new HttpTransportSE(URL, 120000);

        transport.debug = true;

        transport.call(SOAP_ACTION, soapEnvelope);

        response = (Object) soapEnvelope.getResponse();

        int cols = ((SoapObject) response).getPropertyCount();

        Object objectResponse = (Object) ((SoapObject) response)
                .getProperty("Resp");

        SoapObject subObject_Resp = (SoapObject) objectResponse;


        modelObject = new ResposeXmlModel();

        String MsgId = subObject_Resp.getProperty("MsgId").toString();


        modelObject.setMsgId(MsgId);

        String OrgId = subObject_Resp.getProperty("OrgId").toString();


        modelObject.setOrgId(OrgId);

        String ResCode = subObject_Resp.getProperty("ResCode").toString();


        modelObject.setResCode(ResCode);

        String ResDesc = subObject_Resp.getProperty("ResDesc").toString();


        modelObject.setResDesc(ResDesc);

        String TimeStamp = subObject_Resp.getProperty("TimeStamp")
                .toString();


        modelObject.setTimestamp(ResDesc);

        return response.toString();

    } catch (Exception ex) {

        ex.printStackTrace();

        return null;
    }

}
Sundararaj Govindasamy
  • 7,142
  • 5
  • 41
  • 67
Mani
  • 44
  • 4