Calling a web service from Android

Put your problem here if it does not fit any of the other categories.

Calling a web service from Android

Postby Lex » Sat Dec 22, 2007 9:43 am

Hi,
Im trying to receive data from a Web Service. I'm using KSOAP2. Here's my code
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.google.android.Test;
  2.  
  3.  
  4. import org.ksoap2.SoapEnvelope;
  5. import org.ksoap2.serialization.SoapObject;
  6. import org.ksoap2.serialization.SoapSerializationEnvelope;
  7. import org.ksoap2.transport.HttpTransport;
  8.  
  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.widget.TextView;
  12.  
  13. public class myWebService extends Activity
  14. {
  15.          private static final String SOAP_ACTION = "HelloYou";
  16.      private static final String METHOD_NAME = "getHello";
  17.      private static final String NAMESPACE = "urn:HelloYou";
  18.      private static final String URL = "http://localhost/lab/service.php";
  19.      private Object resultRequestSOAP = null;
  20.      
  21.             @Override
  22.             public void onCreate(Bundle icicle)
  23.             {
  24.                 super.onCreate(icicle);
  25.                 TextView tv = new TextView(this);
  26.                 setContentView(tv);
  27.                
  28.  
  29.             SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  30.  
  31.  
  32.              //SoapObject
  33.             request.addProperty("firstname", "John");
  34.             request.addProperty("lastname", "Williams");
  35.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  36.             envelope.setOutputSoapObject(request);
  37.            
  38.  
  39.             HttpTransport androidHttpTransport = new HttpTransport(URL);
  40.             try
  41.             {
  42.                 androidHttpTransport.call(SOAP_ACTION, envelope);
  43.                 resultsRequestSOAP =  envelope.getResponse();
  44.                 String[] results = (String[])  resultsRequestSOAP;
  45.                 tv.setText( results[0]);
  46.             }
  47.             catch (Exception aE)
  48.             {
  49.                 aE.printStackTrace ();;
  50.             }
  51.            }
  52. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


I'm getting an Error because the IO/Connector is missing ? Is there any other way to retrieve data from a webservice then ?
Lex
Developer
Developer
 
Posts: 30
Joined: Fri Nov 16, 2007 11:03 pm

Top

Postby plusminus » Sat Dec 22, 2007 4:58 pm

Hello Lex,

never worked with ksoap before, but perhaps this is appropriate for you :arrow: :src: (click).

Regards,
pluminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Lex » Sat Jan 05, 2008 3:43 pm

Ok it works fine now.
The problem came from my adress http://localhost. I replaced it with my actual IP adress and its okay.

Though now I have a problem concerning KSOAP.
When my return data is a simple type (int, String), I can read it.
But when my return data is a complex type (String[], int[] ), I can't read it back ! I've got a ClassCastException
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. try
  3.  
  4.          {
  5.  
  6.              androidHttpTransport.call(SOAP_ACTION, envelope);
  7.  
  8.              resultsRequestSOAP =  envelope.getResponse();
  9.  
  10.              String[] results = (String[])  resultsRequestSOAP;
  11.  
  12.              tv.setText( results[0]);
  13.  
  14.          }
  15.  
  16.  
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


Can any tell me how to deserialize correctly the return data ?
Lex
Developer
Developer
 
Posts: 30
Joined: Fri Nov 16, 2007 11:03 pm

Postby venkat » Sat Jan 05, 2008 8:08 pm

Hi Lex :),
Can you attach source code of php file, So that it's useful to me to test your program.

Thanks and Regards,
Venkat. :)
venkat
Senior Developer
Senior Developer
 
Posts: 152
Joined: Tue Nov 27, 2007 5:42 am
Location: India

Postby Cybermat » Sun Jan 13, 2008 10:28 am

Hi Lex, not sure if you were able to solve your problem, but I ran into the same issue and I was able to solve it using the following method. I hope it solves your issue. If not, let me know and post your SOAP return in XML format. So that it would be easier for us to troubleshoot.

HttpTransport androidHttpTransport = new HttpTransport(URL);
try
{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
Vector XXXX = (Vector) resultsRequestSOAP.getProperty("[Data element name]");


Just treat the Vector as a normal Java vector, then you should be able to pull all your data
element out


}
catch (Exception aE)
{
aE.printStackTrace ();;
}
}
Cybermat
Junior Developer
Junior Developer
 
Posts: 11
Joined: Mon Dec 03, 2007 5:42 am

Postby chitgoks » Wed Mar 12, 2008 7:15 am

hi lex, did you add the ksoap libs using eclipse? or are you using ant to compile?

i dont use an IDE and im very intrested in accessing my webservice, passing parameters and getting the result xml string :)
Website/Java Games: http://www.chitgoks.com
Blogs:
http://tech.chitgoks.com
http://wuhtevah.chitgoks.com
http://disneyusa.blogspot.com
chitgoks
Developer
Developer
 
Posts: 36
Joined: Tue Mar 11, 2008 3:06 am

Top

Postby cbraun75 » Tue May 20, 2008 3:57 pm

Hi have the same problem as Lex,

want to made the solution from cybermate but my coldfusion server can't made a array with names and if i made a
Code: Select all
...
<cfset response = structnew()>
   <cfset response.vname = arguments.vname>
   <cfset response.nname = arguments.nname>     
<cfreturn response>

as the return type of the webservice i made with coldfusion I must set the returntype to any and then the vectorthings don't work and a Exception is thrown

Maybe somebody can have another solution for the Problem lex has.
When i made a array without an key value and make a getProperty(0) then i get the whole object back ....

Hope someone has a solution for me.

Thanxx!!!
cbraun75
Junior Developer
Junior Developer
 
Posts: 23
Joined: Mon Jan 28, 2008 9:12 pm
Location: Munich

Very helpful but not quite!

Postby dp » Mon Nov 10, 2008 6:10 am

I have been using Web Services in .NET and was following this discussion thread. There was one important tweak I made to make it work with .NET WS. You must specify envelope.dotNet = true; before using the envelope for making the soap call.
dp
dp
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Nov 10, 2008 6:01 am

Postby netmercury » Thu Nov 27, 2008 10:53 am

I have the same problem as well!!!!

I have set up the webservice with java and deployed into tomcat.
I am using ksoap2 as webservice client in my app.

Couldn't cast the develope.getResponse() into any type....
Anyone has solution?

Thank you.
netmercury
Freshman
Freshman
 
Posts: 3
Joined: Sun Nov 16, 2008 5:33 pm

Postby sooraj.rit » Tue Feb 03, 2009 11:54 am

Hi i want to implement a webmethod to search some data and I have done it well in C#.net . Now i want to access that method from android . The real problem I am facing is that, I have to use a complex data type. ( a class containing two strings ). when I call the webmethod, an exception is thrown (Runtime exception saying -" cannot serialize my class "). I have attached code.pls help me.


I am using a class to hold my data as

class PAT_DETAILS
{
String PatName;
String PatID;
}

and in my java code

public class SearchData extends Activity
{
private static final String SOAP_ACTION = "http://MobWebService.org/GetPatDetails";
private static final String METHOD_NAME = "GetPatDetails";
private static final String NAMESPACE = "http://MobWebService.org/";
private static final String URL = "http://10.1.26.21/Webservice/SearchService.asmx";
PAT_DETAILS m_PatDetails;

@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_PatDetails.PatName = "John";
m_PatDetails.PatID ="123";

SoapObject request = new SoapObject( NAMESPACE, METHOD_NAME );
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
envelope.dotNet = true;
// request.addProperty( "PatientName", patname );
// request.addProperty( "PatID", patientId );

request.addProperty( "patientDetails", m_PatDetails );
envelope.setOutputSoapObject( request );
HttpTransportSE htransport = new HttpTransportSE( URL );
try
{

try
{
htransport.call( SOAP_ACTION, envelope ); // throws exception
}
catch( IOException exp )
{
exp.printStackTrace();
}
SoapObject ResultRequestSOAP = (SoapObject)envelope.bodyIn;

// Remaining codesnippet here......
}
catch ( Exception aE )
{
aE.printStackTrace (); //Runtime exception here - "cannot serialize my class "
}
}
sooraj.rit
Freshman
Freshman
 
Posts: 5
Joined: Tue Jan 13, 2009 12:29 pm
Location: Trivandrum,India

Postby tamperen » Mon Apr 27, 2009 8:51 am

i can get the hello World Working but i cant seem to get the parameter work .....




request.addProperty("A", "John");

-----------------------------------------------------------------------------------------------------------------
my web service
<WebMethod()> _
Public Function HelloWorld(ByVal A As String) As String

Return "Hello World " + A

End Function

------------------------------------------------------------------------------------------------------------
is there more stuff to be done other than just doing


request.addProperty("A", "John");


plz help me

and thank you in advance
tamperen
Freshman
Freshman
 
Posts: 2
Joined: Mon Apr 06, 2009 7:19 am

Postby desuvinodkumar » Thu Jul 16, 2009 7:57 am

Hi
if there is no property in that method means how can we go furthewr
i am not getting XML response .....
it is in diff format

like this...

IndexContestInfo{item=anyType{name=Ankitha; totalimages=2; rating=2.5; }; item=anyType{name=Anushka; totalimages=4; rating=9.5; }; item=anyType{name=Apsara; totalimages=1; rating=0; };

is there any posiblilities to convert this into xml or any other way to parse this response...

thanks a lo in advance....
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Problem while calling the web services in android (URGENT)

Postby karthick » Thu Aug 06, 2009 1:15 pm

Problem while calling the web services in android.':(' ':?:'

To call web services in android I have done the following steps

1. Wrote the web service class in java and stored in apache axis. (in .jws format)


public class ADD2No
{
public int add(int a,int b)
{
return (a+b);
}

public int sub(int c,int d)
{
return (c-d);
}
}

2. Then is have tested the web service on web browser.

http://192.168.1.41:8081/axis/ADD2No.jws

I have got.

There is a Web Service here
Click to see the WSDL
in browser.
3. then I implement the service using core java and Ksoap2 library. Its working fine.

4. But I got error when I call the web service via android.

5. This is my code.

package com.example.SamWebService;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class WebServiceInAndroid extends Activity
{
/** Called when the activity is first created. */

/*
private static final String SOAP_ACTION = "HelloYou";
private static final String METHOD_NAME = "getHello";
private static final String NAMESPACE = "urn:HelloYou";
private static final String URL = "http://localhost/lab/service.php";
*/

private static final String SOAP_ACTION = "ADD2No";
private static final String METHOD_NAME = "add";
private static final String NAMESPACE = "urn:ADD2No";
private static final String URL = "http://elcserver:8081/axis/ADD2No.wsdl";


//private Object resultsRequestSOAP = null;


@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);

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

setContentView(R.layout.main);

try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("a", 3);
request.addProperty("b", 4);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);

try
{
androidHttpTransport.call(SOAP_ACTION, envelope);

//Parse Response

SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

//String xy = resultsRequestSOAP.getProperty(0).toString();

tv.setText("Ganzes Rückagbeobjekt:n"+resultsRequestSOAP.toString());




}

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

}
catch(Exception e)
{
tv.setText("Error : " + e.getMessage());
}


}



}
6. I have tried lot of methods still I am getting the error.
“Your application has been stopped unexpectedly”

7. my application’s manifest file is

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.SamWebService"
android:versionCode="1"
android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".WebServiceInAndroid"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

<uses-permission xmlns:android="http://schemas.android.com/apk/res/android" android:name="android.permission.INTERNET"></uses-permission>

<uses-sdk android:minSdkVersion="3" />
</manifest>

8. So give me solutions to overcome this problem and how to define the SOAP_NAME, METHOD_NAME, NAMESPACE and URL what they meant really.

9. Give me the step by step procedure to call apache axis web services from android.



:(

Regards,
Karthick
hi i am here to share my knowledge
karthick
Freshman
Freshman
 
Posts: 3
Joined: Thu Aug 06, 2009 10:34 am

Postby desuvinodkumar » Thu Aug 06, 2009 1:31 pm

HI karthick

SOAP_Action,
METHOD_NAME, from which method u were accesing form the server ....
NAMESPACE
URL Means Server name where exaclt the server scripting file is there that location

In the above example is already give clearly....

private static final String SOAP_ACTION = "getMessage"; //Method in web services
private static final String METHOD_NAME = "getMessage"; // Method which we are calling
private static final String NAMESPACE = "http://rpc.xml.coldfusion";
private static final String URL = "http://192.168.1.7:8500/DA/ws_functions/test6.cfc?wsdl"; //web services

u will get response from the server for the Above code.....
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Postby ohyes » Fri Aug 14, 2009 8:48 am

Dear ALL,

Please help me fix the bug caused by the text in bold.
androidHttpTransport.call(SOAP_ACTION, envelope); //Throw exception here!!!

My Java code is the following:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld";
  2.         private static final String METHOD_NAME = "HelloWorld";
  3.         private static final String NAMESPACE = "http://tempuri.org/";
  4.         private static final String URL = "http://127.0.0.1:1483/WebSite2/Service.asmx";
  5.  
  6.         @Override
  7.         public void onCreate(Bundle savedInstanceState) {
  8.                 super.onCreate(savedInstanceState);
  9.                 setContentView(R.layout.main);
  10.  
  11.                 mResult = (EditText) findViewById(R.id.result);
  12.                 try {
  13.                         SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  14.  
  15.                         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  16.                         envelope.dotNet = true;
  17.                         envelope.setOutputSoapObject(request);
  18.                         AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
  19.                         try {
  20.                                 <span style="font-weight: bold">androidHttpTransport.call(SOAP_ACTION, envelope);</span> //Throw exception here!!!
  21.                                 SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
  22.                                 mResult.setText("Ganzes Rückagbeobjekt:n");// +resultsRequestSOAP.toString());
  23.                         }
  24.  
  25.                         catch (Exception e) {
  26.                                 mResult.setText("NG1n");
  27.                         }
  28.  
  29.                 } catch (Exception e) {
  30.                         mResult.setText("NG2n");
  31.                 } finally {
  32.                         mResult.setText("NG3n");
  33.                 }
  34.         }
  35.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


The server side's code is as follow:
Code: Select all
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }   
}


Thank you in advance,

--
Ohyes.
Attachments
WS3.PNG
WS3.PNG (20.06 KiB) Viewed 127235 times
WS2.PNG
WS2.PNG (19.54 KiB) Viewed 127235 times
WS1.PNG
WS1.PNG (19.04 KiB) Viewed 127235 times
ohyes
Junior Developer
Junior Developer
 
Posts: 10
Joined: Fri Jul 10, 2009 2:51 am

Top
Next

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 18 guests