Call .NET web service in Android
Asked Answered
C

3

8

My .NET web service returns an XML. When I call the web service with ksoap2 in Android, I have this issue. Please help.

My Logcat in Eclipse

12-19 15:58:11.951: W/dalvikvm(2041): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-19 15:58:11.961: E/AndroidRuntime(2041): FATAL EXCEPTION: main
12-19 15:58:11.961: E/AndroidRuntime(2041): java.lang.RuntimeException: double ID
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:407)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.parseBody(SoapSerializationEnvelope.java:151)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:140)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.Transport.parseResponse(Transport.java:116)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:259)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:114)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.example.webservicee.MainActivity$1.onClick(MainActivity.java:133)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.view.View.performClick(View.java:2408)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.view.View$PerformClick.run(View.java:8816)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Handler.handleCallback(Handler.java:587)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Looper.loop(Looper.java:123)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at java.lang.reflect.Method.invokeNative(Native Method)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at java.lang.reflect.Method.invoke(Method.java:521)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

MainActivity.java

package com.example.webservicee; 
import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
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 org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    final static String NAMESPACE = "http://tempuri.org/";

    final static String METHOD_NAME = "GetContent";

    final static String SOAP_ACTION = "http://tempuri.org/GetContent";

    final static String URL = "http://www.example.com/XMLGenerator/GenerateXML.asmx";


    private Button Mybtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        deger = (EditText) findViewById(R.id.deger);
        sonuc = (TextView) findViewById(R.id.flag);
        Mybtn = (Button) findViewById(R.id.hesapla);
        Mybtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

                //My webservice paramaters 
                Request.addProperty("SectionsInclude","10");
                Request.addProperty("DocumentCount",10);
                Request.addProperty("SortBy","0");
                Request.addProperty("SortOrder","ASC");
                Request.addProperty("UserName","myuser");
                Request.addProperty("Pass","Lsss");
                /**/
                      /*  PropertyInfo pi=new PropertyInfo();
                        pi.setName("arg0");
                        pi.setValue("10");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg1");
                        pi.setValue(10);
                        pi.setType(Integer.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg2");
                        pi.setValue("0");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg3");
                        pi.setValue("ASC");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();

                        pi.setName("arg4");
                        pi.setValue("myuser");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg5");
                        pi.setValue("Lsss");
                        pi.setType(String.class);
                        Request.addProperty(pi);


                        */


                SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                soapEnvelope.dotNet = true;
                soapEnvelope.setOutputSoapObject(Request);
                //soapEnvelope.bodyOut = Request;
                HttpTransportSE aht = new HttpTransportSE(URL);
                try {
                    aht.call(SOAP_ACTION, soapEnvelope);


                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String result;
                try {

                    result = "Fahrenheit:"+(SoapPrimitive) soapEnvelope.getResponse();
                     Log.d("--Result-- ", result);
                    //sonuc.setText(result);

                    } catch (SoapFault e) 
                    {

                    e.printStackTrace();

                    }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

This is the example response xml:

<?xml version="1.0" encoding="utf-8"?>
<liste>
<document id="6" titles="bestPeople" showingDate="27.09.2011 00:00:00"  date="27.09.2011 00:00:00" ContentID=rbHe8zKvDTG7TLS" >
<part id="6" baslik="best" icerik="&lt;table style=&quot;width: 188px; height: 24px;&quot; border=&quot;tbody&gt;&#xD;&#xA;&lt;/table&gt;" resim="">
<SecNotes><![CDATA[]]></SecNotes>
<ContNotes><![CDATA[]]></ContNotes>
</part>
<SecNotes><![CDATA[]]></SecNotes>
<ContNotes><![CDATA[]]></ContNotes>
</document>
</liste>
Cockeye answered 19/12, 2012 at 16:1 Comment(4)
Since the call stack shows a call in progress to HttpTransportSE.call, I'd surmise the location in your code is at or after aht.call(...). Since the call stack also shows SoapEnvelope.parse, aht.call(...) has evidently not returned, so it appears the problem is in the response from your web service.Indices
Hi Erham is your WS published to see the methods? i think your code is not the problem.Citizen
hi @Citizen this my method. thank you. muhabbetsokaklari.com/LEdisXMLGenerator/…Cockeye
well i see you need username/password, could you post an example of the response?Citizen
C
4

I solve it. I added this code. it's working.

my Code

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}
private void init()
{
    //your webservice envelope
    String envelope="<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetContentTreeBySections xmlns=\"http://tempuri.org/\"><SectionsInclude>%s</SectionsInclude><DocumentCount>%s</DocumentCount><SortBy>%s</SortBy><SortOrder>%s</SortOrder><UserName>%s</UserName><Pass>%s</Pass></GetContentTreeBySections></soap:Body></soap:Envelope>";

    String myEnvelope = String.format(envelope, "myParam1 value", "myParam2 value","myParam3 value","myParam4 value");
    String url = "http://www.mywebserice.com/XMLGenerator/GenerateXML.asmx";
    String soapAction = "http://tempuri.org/GetContentTreeBySections"; 
    String response = CallWebService(url, soapAction, myEnvelope);
    //Log.v("response", response);
    Toast.makeText(getApplicationContext(), "this"+response,Toast.LENGTH_LONG).show();
    String xml=response;    
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
String CallWebService(String url,String soapAction,String envelope) 
{

      final DefaultHttpClient httpClient=new DefaultHttpClient();
      // request parameters
      HttpParams params = httpClient.getParams();
         HttpConnectionParams.setConnectionTimeout(params, 10000);
         HttpConnectionParams.setSoTimeout(params, 15000);
         // set parameter
      HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

      // POST the envelope
      HttpPost httppost = new HttpPost(url);
      // add headers
         httppost.setHeader("soapaction", soapAction);
         httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
         String responseString="";

         try 
         {
                // the entity holds the request
                HttpEntity entity = new StringEntity(envelope);
                httppost.setEntity(entity);

                // Response handler
                ResponseHandler<String> rh=new ResponseHandler<String>() {
        // invoked when client receives response
        public String handleResponse(HttpResponse response)
          throws ClientProtocolException, IOException {

         // get response entity
         HttpEntity entity = response.getEntity();

         // read the response as byte array
               StringBuffer out = new StringBuffer();
               byte[] b = EntityUtils.toByteArray(entity);

               // write the response byte array to a string buffer
               out.append(new String(b, 0, b.length));
               return out.toString();
        }
       };

       responseString=httpClient.execute(httppost, rh); 

      }
         catch (Exception e) {
          Log.v("exception", e.toString());
      }

         // close the connection
      httpClient.getConnectionManager().shutdown();
      return responseString;
}
Cockeye answered 25/12, 2012 at 8:17 Comment(2)
Your answer woudl be more useful if you said what you have added/changed to make it workAdamo
@Adamo I tried a lot of tutorial for my webservice that didn't work and later ı tried to this code and working. also ksoap2 didn't work for my webservice. regardsCockeye
F
2

Rather than using ksoap, try using ice-soap library, which is open source. It's far better than ksoap and provides efficient library to send request and parse response using annotatations....

Fob answered 22/12, 2012 at 9:39 Comment(0)
O
1

First of all never use Network Operations in main thread try always to insert network operations inside non-main thread like AsyncTask or any other worker thread. Second use the following code to get the result:

 String message="";
    SoapObject result = (SoapObject)envelope.bodyIn;
    if(result != null)
       {
          message=result.getProperty(0).toString();
       }

and also change the following code

Request.addProperty("DocumentCount",10);

to be

Request.addProperty("DocumentCount","10");
Orv answered 24/12, 2012 at 18:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.