0

i have this code running on android studio:

MainActivity.java

package myname.company.com.soap__03;

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {


    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", "server:port");
        mHeaders.put("Connection", "Keep-Alive");
        mHeaders.put("User-Agent", "AndroidApp");
        // mHeaders.put("Authorization", "Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            Button openButton = (Button) findViewById(R.id.open);

            openButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    try {
                        receiveCurrentShipments("WSDL URL");

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }catch(Exception e) {
            e.printStackTrace();
        }
    }


    public final static InputStream receiveCurrentShipments(String stringUrlShipments) {
        int status = 0;
        String xmlstring = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
                "xmlns:soap=\"someurl\" "+
                "xmlns:gen=\"http://someurl\"> "+
        "<soapenv:Header> "+
        "<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
        "</soapenv:Header> "+
        "<soapenv:Body> "+
        "<gen:getGenericResult> "+
        "<Request> "+
        "<dataItem> "+
        "<name>Username</name> "+
        "<type>String</type> "+
        "<value>usernamehere</value> "+
        "</dataItem> "+
        "<dataItem> "+
        "<name>Password</name> "+
        "<type>String</type> "+
        "<value>passwordhere</value> "+
        "</dataItem> "+
        "</Request> "+
        "</gen:getGenericResult> "+
        "</soapenv:Body> "+
        "</soapenv: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://NAMESPACE\METHOD_NAME");

            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;
    }
}

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:padding="16dp">



    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@color/colorPrimaryDark"

        android:elevation="4dp"
        android:paddingLeft="70dp"
        android:paddingRight="70dp"
        android:text="Soap Call"
        android:textColor="#fff" />
</LinearLayout>

below is my output:

02/28 14:33:49: Launching app Cold swapped changes. $ adb shell am start -n "mokhethea.vodacom.com.soap__03/myname.company.com.soap__03.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Connected to process 30654 on device vodafone-vfd_500-TK8HFQ7PYHNNNBCE I/InstantRun: Instant Run Runtime started. Android package is myname.company.com.soap__03, real application class is null. E/MultiWindowProxy: getServiceInstance failed! D/libc-netbsd: [getaddrinfo]: hostname="WSDL URL and Port"; servname=(null); netid=0; mark=0 D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0 D/libc-netbsd: [getaddrinfo]: hostname="WSDL URL and Port"; servname=(null); netid=0; mark=0 D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0 I/HTTP Client: HTTP status code : 0

sample code was extracted from: Владимир Лапенков article: How to call a SOAP web service on Android

anyone can tell where i am getting wrong/ rather provide a working example..?

Community
  • 1
  • 1
Manyalo
  • 81
  • 1
  • 5
  • I found the solution to this. the solution is to use AsyncTask: https://developer.android.com/reference/android/os/AsyncTask.html – Manyalo Mar 01 '17 at 11:38

1 Answers1

0

Glad you asked this question, i faced the same problem when i started out with soap webservice. The key here is to avoid using soap libraries and go for the classes that java has provided to make the request and parse it i.e http,DOM parser or SAX parser. This is how you make your request without using ksoap or any other libraries.

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

private class runTask extends AsyncTask<String, String, String> {

            private String response;
            String string = "your string parameter"
            String SOAP_ACTION = "your soap action here";

            String stringUrl = "http://your_url_here";
            //if you experience a problem with url remove the '?wsdl' ending



            @Override
            protected String doInBackground(String... params) {

                try {

                            //paste your request structure here as the String body.


                    String body = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
            "xmlns:soap=\"someurl\" "+
            "xmlns:gen=\"http://someurl\"> "+
    "<soapenv:Header> "+
    "<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
    "</soapenv:Header> "+
    "<soapenv:Body> "+
    "<gen:getGenericResult> "+
    "<Request> "+
    "<dataItem> "+
    "<name>Username</name> "+
    "<type>String</type> "+
    "<value>usernamehere</value> "+
    "</dataItem> "+
    "<dataItem> "+
    "<name>Password</name> "+
    "<type>String</type> "+
    "<value>passwordhere</value> "+
    "</dataItem> "+
    "</Request> "+
    "</gen:getGenericResult> "+
    "</soapenv:Body> "+
    "</soapenv:Envelope>";


                    try {
                        URL url = new URL(stringUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);
                        conn.setDefaultUseCaches(false);
                        conn.setRequestProperty("Accept", "text/xml");
                        conn.setRequestProperty("SOAPAction", SOAP_ACTION);
                        //you can pass all your request parameters here usong .setRequestProperty() method

                        //push the request to the server address

                        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                        wr.write(body);
                        wr.flush();

                        //get the server response

                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder builder = new StringBuilder();
                        String line = null;

                        while ((line = reader.readLine()) != null) {


                            builder.append(line);
                            response = builder.toString();//this is the response, parse it in onPostExecute

                        }


                    } catch (Exception e) {

                        e.printStackTrace();
                    } finally {

                        try {

                            reader.close();
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }


                } catch (Exception e) {

                    e.printStackTrace();
                }

                return response;
            }

            /**
             * @see AsyncTask#onPostExecute(Object)
             */
            @Override
            protected void onPostExecute(String result) {



               try {

                  Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

                  //Go ahead and parse the response now

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

Now in your onCreate just go ahead and execute this class using the following code

runTask task = new runTask();
task.execute();

If the url and request body is correctly fed,you will get your response in your onPostExecute, format and parse it from here. The main advantages of using this libraryless way is that it is flexible, you can format the request in any way the webservice requires as compared to the libraries which you only use the provided request formats. This solution works seamlessly in my code, feel free to ask for any further clarification.

Gordon developer
  • 387
  • 3
  • 13