When trying to access Magento SOAP web services v2 from Android, after some searching on web, I found that ksoap2-android project could be useful to implement SOAP client in android project. (Ksoap2-android is lightweight and efficient SOAP client library for android platform).
Next step was to figure-out how to use it.
After some additional investigation, I found that it is pretty simple to use, when you get used to it once.
First of all, let’s create new Android project, I set it to be for android 2.3.3. After creating new project, we need to download and import ksoap2-android library inside the project and add it to build path.
Ksoap2-android library can be downloaded from here (http://code.google.com/p/ksoap2-android/downloads/detail?name=ksoap2-android-assembly-2.4-jar-with-dependencies.jar&can=2&q=)
When download ksoap2-android-assembly-2.4-jar-with-dependencies.jar, make additional folder inside your android project, call it for example “lib” and paste ksoap2-android-assembly-2.4-jar-with-dependencies.jar there.
After that, right click on pasted file in package explorer (assuming that you are using Eclipse) and choose: Build Path -> Add To Build Path.
Of course, If we want to access Magento web services SOAP API, we need to go to Magento installation’s admin area and under System/Web services/Roles create Role with appropriate resources (for development purpose, we can mark them all), and then System/Web services/Users create new API user.
After that we need to assign roles we created to user in order to make the whole thing work. We will need user-name and apiKey from there to be able to log-in with our SOAP client.
Now, we are ready to start developing out test application.
As I said, this example is for tutorial purposes – only, and it’s not right way to make Http requests from main Activity, but is just for purposes of this article, so we will now write out code inside Main Activity’s onCreate method:
package com.soap.test;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SoapTestActivity extends Activity {
/** Called when the activity is first created. */
private static final String NAMESPACE = "urn:Magento";
private static final String URL = "http://yourhost.com/api/v2_soap/";
@Override
public void onCreate(Bundle savedInstanceState) {
//our code goes here
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Fist we are going to create and set new SoapSerializationEnvelope:
//...
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
} catch (Exception e) {
e.printStackTrace();
}
//...
After that, lets create our request object and assign it to envelope. We are going first to call “login” method to Magento API in order to authenticate and retreive the sessionId.
//...
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, "login");
request.addProperty("username", "mobile");
request.addProperty("apiKey", "mobile123");
env.setOutputSoapObject(request);
} catch (Exception e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Of course, we have to add request parameters to login method, and it’s done with request.addProperty and then assign request object to envelope.
After that, we need to call SOAP method and retrieve result. so, here is complete Activity source code:
package com.soap.test;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SoapTestActivity extends Activity {
/** Called when the activity is first created. */
private static final String NAMESPACE = "urn:Magento";
private static final String URL = "http://yourhost.com/api/v2_soap/";
@Override
public void onCreate(Bundle savedInstanceState) {
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, "login");
request.addProperty("username", "mobile");
request.addProperty("apiKey", "mobile123");
env.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call("", env);
Object result = env.getResponse();
Log.d("sessionId", result.toString());
} catch (Exception e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
We retrieved session id as can be seen in LogCat window:
After this basic steps, we just have to make SOAP calls same way to other web service methods, and provide retrieved sessionId in each call.
For example, let’s call customerCustomerList method to retrieve list of customers:
package com.soap.test;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SoapTestActivity extends Activity {
/** Called when the activity is first created. */
private static final String NAMESPACE = "urn:Magento";
private static final String URL = "http://yourhost.com/api/v2_soap/";
@Override
public void onCreate(Bundle savedInstanceState) {
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, "login");
request.addProperty("username", "mobile");
request.addProperty("apiKey", "mobile123");
env.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call("", env);
Object result = env.getResponse();
Log.d("sessionId", result.toString());
//making call to get list of customers
String sessionId = result.toString();
request = new SoapObject(NAMESPACE, "customerCustomerList");
request.addProperty("sessionId",sessionId );
env.setOutputSoapObject(request);
androidHttpTransport.call("", env);
result = env.getResponse();
Log.d("Customer List", result.toString());
} catch (Exception e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
As we can see in LogCat window, we got customer list object with child objects as response.
If you want to find out what methods in Magento API v2 are available and what parameters should be used for request, just open URL: http://yourhost.com/api/v2_soap/?wsdl=1 and you will see all available methods and their request and response parameters that can be used.
Of course, don’t forget to set android.permission.INTERNET in AndroidManifest.xml file.
Hope that you will find this post helpful in own projects. Cheers!











Hey,
Thank you for this posting code.
But when ever i try to run this, i am getting NoClassDefFoundError exception.
Here is my log:
…
Also it seems HttpTransportSE is not present in the ksoap jar file. I am getting error when i include the same. I replaced this with HttpTransport.
Please let me know what i am doing wrong.
Thank You,
Vineet Rao
@Vineet, I am sorry, little mistake in link to ksoap android library. I edited post, so you can download proper library now.
Hi,
Thanks for the code.
But, I am getting the exception at line 42,where you are calling the webservice.The exception is “XmlPullParser exception expected START_TAG…..”. I tried to find solution on google but i can’t get.
So,Please reply me what is going wrong
Thanks in advance
Hello
You have explain fantastically and in very easy manner.
But It is not working for me.
when I tried same code, XmlPullParser exception expected START_TAG…..” exception is raised.
I surf many website to find solution , but I can’t get it.
Please help me.
Thanks in advance.
I am sorry, but I can not reproduce your problem right now. Please try to check if soap output is in proper xml format or you are getting something else in response from server. It seems to me that you didn’t get proper SOAP response.
Hey I got above solution.I have changed URL and problem is solved. But will you please help me again ? I am facing another problem.
I got the response from server but now I want to pass filter in this customerCustomerList. I aam using below code for it. But it says java.lang.runtimeException in serializing… Code is
ArrayList<HashMap<String,HashMap<String, Integer>>> filter= new ArrayList<HashMap<String,HashMap<String,Integer>>>(); HashMap<String, Integer> condition=new HashMap<String, Integer>(); condition.put("customer_id",1); HashMap<String,HashMap<String,Integer>> filterarray=new HashMap<String, HashMap<String,Integer>>(); filterarray.put("item",condition); filter.add(filterarray); request.addProperty("filters",filter);I just found the help for php code only. But nowhere is given help for filters in JAVA. php code is as below,
$complexFilter = array( 'complex_filter' => array( array( 'key' => 'group_id', 'value' => array('key' => 'in', 'value' => '1,3') ) ) ); $result = $client->customerCustomerList($session, $complexFilter);Thanks for previous reply and as well as for next reply.
Cheers.
Dear Sir
I installed Magento in my local drive so my link is http://localhost/magento/api/v2_soap/ right??
I get error and can not get Customer List .. i am sending you my log .. please help me ..
09-19 11:02:22.149: D/OpenGLRenderer(4389): Flushing caches (mode 0)
09-19 11:02:28.229: E/PhonePolicy(4446): Could not preload class for phone policy: com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback
09-19 11:02:28.289: D/step1(4446): 11111111111111
09-19 11:02:28.299: W/System.err(4446): android.os.NetworkOnMainThreadException
09-19 11:02:28.299: W/System.err(4446): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-19 11:02:28.299: W/System.err(4446): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-19 11:02:28.299: W/System.err(4446): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-19 11:02:28.299: W/System.err(4446): at java.net.InetAddress.getAllByName(InetAddress.java:220)…
…….
[comment is shortened by the author]
@anurag, it seems to me that you are trying to reach localhost domain from android emulator or attached device to your computer.
I don’t think that this is possible to accomplish this way because of some Android limitations.
Please make sure to get some external domain name and then try to connect to your local web server via external ip/URL address.
Second possibility of this problem is maybe that you forgot to allow internet access in your Android manifest.
Hey Amit,
Please, help me. M getting the XMLPullParser error in andorid while connecting to magento web service.
Please, give me your email id asap.
mine is vijaysinghbca9@gmail.com
-Vijay
@Vijay, would you be so kind to read http://inchoo.net/ecommerce/magento/magento-v2-soap-demystified/ and here you will find an answer on how to get SOAP web service working on Magento and also to see if you missed to configure something or even if you entered wrong URL for SOAP.
Thanks U so much sir for your quick reply.
I have include the following library..
ksoap2-android-assembly-2.4-jar-with-dependencies.jar in my android project.
I had also created the web service user and role and assignment role to user in magento.
I have installed magento 1.7 on my local machine.
Following is the code… pls tell me where I am going wrong and what else is required to configure.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final String NAMESPACE = “urn:Magento”;
private static final String URL = “http://192.168.1.60:81/magento/index.php/api/v2_soap/”;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
//System.setProperty(“http.keepAlive”, “false”);
SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
env.encodingStyle = SoapEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, “login”);
request.addProperty(“username”, “dev”);
request.addProperty(“apiKey”, “aaaa”);
env.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.setXmlVersionTag(“”);
androidHttpTransport.debug = true;
Log.d(“vijay”, “vijay”);
try
{
androidHttpTransport.call(“”, env);
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Object result = env.bodyIn;
//Object result = env.getResponse();
Log.d(“vijay”, “vijay”);
Toast.makeText(MainActivity.this, “Hello “+result, Toast.LENGTH_SHORT).show();
Log.d(“sessionId”, result.toString());
} catch (Exception e)
{
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
The link provided by you in above reply, there is some php code, but I am not getting where to write that code if I am developing an android project for consuming magento web services.
Pls, tell me.
Thanx
@Viay, please read the comments above. If you are trying to connect to localhost from same computer’s emulator it will not be possible.
You need to have external IP address of your web server in order to be able to connect to web service. Get yourself Charles application and see what response are you getting from magento.
(Error is not in your code but in accessing Magento’s web service on localhost via Android app)
Thanx alot sir, for your fast n kind reply. I’ll do the things suggested by you. I was just scratching my head.
I think now my problem will be solved. If you don’t mind can you mail me your gmail id please.
Thanx once again.
How to parse CustomList response?
result = env.getResponse();
//What i do?
Thanx a lot for your guidance Sir.
I was trying with SOAP magento api, but didn’t get through. It was still giving XMLPullParser Exception. I didn’t know what was going wrong. However, I got it worked with XMLRPC magento api in my android app. I am able to get the Catalog details in response from server after giving external IP address.
hey Vijay
Please try using another URL.
I was facing same problem and i have tried using another URL.
And its working for me.
Hey Sir
I got stucked at passing filters to retrieve specific customer from list.
Please give me any hint. I have posted a comment but you dint replied yet.
Please respond my question.
Thanks in advance.
i am getting
11-05 18:38:35.445: W/System.err(678): org.xmlpull.v1.XmlPullParserException: expected: END_TAG {http://schemas.xmlsoap.org/soap/envelope/}Body (position:END_TAG @2:221 in java.io.InputStreamReader@4052e378)
error when trying to run this code, help me out
Hi Darko and all,
I am able to sort out my issue and have got session id and response successfully.
Is there any pointer from where i can start parsing the response i received which currently we are showing in logs
@ Dhaval,
U can do the following…
for (Object object : productList) {
i++;
HashMap productMap = (HashMap) object;
productIDs.add(productMap.get("product_id"));
mThumbIds.add(productMap.get("name"));
Log.d("PRODUCT_INFO",
"Your data values are: 'product_id'=> "
+ productMap.get("product_id") + ", 'product_name'=> "
+ productMap.get("name"));
}
here, productList contains reponse from the server.
I Fix the “XmlPullParser exception expected START_TAG…..”. issue
just remove the wsdl from the URL it will work like a charm!!!!
Regards
Meghs
I’m trying to get a list of products that contain a certain string from the server.
this is code i’m running:
PropertyInfo sessionInfo = new PropertyInfo();
sessionInfo.setName(“sessionId”);
sessionInfo.setValue(sessionId);
sessionInfo.setType(PropertyInfo.STRING_CLASS);
PropertyInfo findProductsCall = new PropertyInfo(); findProductsCall.setName(“call”);
findProductsCall.setValue(“product.list”); findProductsCall.setType(PropertyInfo.STRING_CLASS);
SoapObject values = new SoapObject();
values.addProperty(“key”, “like”);
values.addProperty(“value”, text);
SoapObject filters = new SoapObject();
filters.addProperty(“key”, “name”);
filters.addProperty(“value”, values);
PropertyInfo filtersInfo = new PropertyInfo(); filtersInfo.setName(“args”);
filtersInfo.setValue(filters);
filtersInfo.setType(PropertyInfo.VECTOR_CLASS);
// This creates the envelope, calls addProperty on each property passed and uses the HttpTransportSE call method as shown in the example
soapClient.execute(sessionInfo, findProductsCall, filtersInfo);
This is the envelope .toString():
call{sessionId=8dbc5988b25991f9b939bd06e64a0; resourcePath=catalog_product.list; filters={key=name; value={key=like; value=ZZZ; }; }; }
But I keep getting
SoapFault – faultcode: ‘SOAP-ENV:Server’ faultstring: ‘Allowed memory size of 268435456 bytes exhausted (tried to allocate 77 bytes)’ faultactor: ‘null’ detail: null
I have access to the admin page of the server. There is only one Product With three ‘Z’s, incidentally named ZZZ. Can anyone help? The soap api v1 defines the call method like this
Note that I have successfully used the call method to get categories. What am I doing wrong with the filters?
Thank you a great deal for this tutorial. It really was a life saver =)
I made an error in the code presented in the snippet above:
where reads
findProductsCall.setName(“call”);
I was actually using
findProductsCall.setName(“filters”);
if I use
findProductsCall.setName(“call”);
the error changes to
java.lang.NullPointerException
Hi Darko,
I am trying out same example. But its not working in my case.
I am using Magento 1.6.2
Is there any issue with this version.
On which version you have tried this example?
Thanks.
Hello, Amit how to write below code in java
$complexFilter = array(
‘complex_filter’ => array(
array(
‘key’ => ‘group_id’,
‘value’ => array(‘key’ => ‘in’, ‘value’ => ’1,3′)
)
)
);
hi Darko,
Can you pls tell me how to add product to shoppingCartProductAdd function using ksop2