How to pass Custom Arraylist to Soap web service? - android

thanks for reading my problem,
i am trying to pass Custom ArrayList to SOAP service which gives me cannot serialize exception,
here is my code
// Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_CALL);
UserInfo userInfo = new UserInfo();
userInfo.name = "xyz";
userInfo.keyName = "name";
userInfoList.add(userInfo);
UserInfo userInfo1 = new UserInfo();
userInfo1.email = "xcv#gmail.com";
userInfo1.keyEmail = "email_id";
userInfoList.add(userInfo1);
UserInfo userInfo2 = new UserInfo();
userInfo2.mobile = "9876543210";
userInfo2.keyMob = "mobileno";
userInfoList.add(userInfo2);
UserInfo userInfo3 = new UserInfo();
userInfo3.regId = "xyz";
userInfo3.keyRegId = "registrationid";
userInfoList.add(userInfo3);
UserInfo userInfo4 = new UserInfo();
userInfo4.appVersion = "1.0";
userInfo4.keyAppVersion = "appversion";
userInfoList.add(userInfo4);
UserInfo userInfo5 = new UserInfo();
userInfo5.xmlString =
"<?xml version=\"1.0\" encoding=\"UTF- 8\"standalone=\"no\"?>"
+ "<a><s><s>"
+ "<d>d</d>"
+ "<f>f</f>"
+ "</a>"
userInfo5.keyXmlString = "xml_string";
userInfoList.add(userInfo5);
request.addProperty("method", "addDeviceInfo");
request.addProperty("parameter", userInfoList);
Log.e("request", "--->>> " + request);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
Log.e("1111", "1111");
envelope.setOutputSoapObject(request);
Log.e("222", "222");
envelope.dotNet = false;
envelope.bodyOut = request;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
Log.e("333", "3333");
// Needed to make the internet call
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Log.e("44444", "44444");
androidHttpTransport.debug = true;
try {
Log.e("55555", "55555");
// this is the actual part that will call the webservice
androidHttpTransport.call(MainActivity.SOAP_ACTION, envelope);
Log.e("Request", androidHttpTransport.requestDump);
Log.e("Response", androidHttpTransport.responseDump);
} catch (Exception e) {
e.printStackTrace();
}
try {
SoapObject result = (SoapObject) envelope.bodyIn;
Log.e("result", "--->> " + result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
problem is i get everything proper but when it comes to androidHttpTransport.call(MainActivity.SOAP_ACTION, envelope);
is says java.lang.RuntimeException: Cannot serialize: [com.example.soapdemo.UserInfo#40da80a8]
here is my user info class
package com.example.soapdemo;
import java.io.Serializable;
import java.util.Hashtable;
import org.apache.http.entity.SerializableEntity;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
public class UserInfo implements Serializable {
public String keyName;// = "name";
public String name;
public String keyEmail;// = "email_id";
public String email;
public String keyMob;// = "mobile_no";
public String mobile;
public String keyRegId;// = "registration_id";
public String regId;
public String appVersion;
public String keyAppVersion;
public String xmlString;
public String keyXmlString;
}
help me resolving this is, any reply is very appreciable
Thanks in advance
i have already gone through many pages but could not solve this issue
i will really appreciate if any one can solve this issue and help me out
thank you very much

Related

Connecting to external webservice fail to response on Android

I'm trying to connect to a external webservice from an Android app, but currently it crashes on the XML response, please help me notice if the call structure is built incorrectly or any the response code is crashed. Here is my code:
public class sri extends AsyncTask<String, String, String>
{
public final static String URL = "http://qa-suia.ambiente.gob.ec:8092/suiawebservices/SuiaServices?wsdl";
public static final String NAMESPACE = "http://client.ambiente.gob.ec/";
public static final String SOAP_ACTION_PREFIX = "/";
private static final String METHOD = "getRuc";
private String resp;
SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
protected String doInBackground(String... param)
{
SoapObject request = new SoapObject(NAMESPACE,METHOD);
//String JsonString=Serializa();
request.addProperty("user","99999999");
request.addProperty("pass","xxxxxxxxxxxx");
request.addProperty("rucNumber","99999999999");
//sobre.dotNet=true;
sobre.setOutputSoapObject(request);
try
{
HttpTransportSE transporte=new HttpTransportSE(URL);
transporte.call(NAMESPACE+METHOD, sobre);
} catch (Exception e)
{
String msn="error";
return msn;
}
try {
if (sobre != null) {
SoapPrimitive response = (SoapPrimitive)sobre.getResponse();
resp=response.toString();
}
else
{
}
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
protected void onProgressUpdate(Integer... values)
{
}
public void onPreExecute()
{
}
public void onPostExecute(String result)
{
String resultado=result;
}
Here's working code for what I'm doing calling a .Net Service (It looks like you're not putting your request into an envelope):
private static SoapPrimitive callProcServiceForScalar(String serviceMethod, String storedProc, String params) throws Exception {
String NAMESPACE = "http://" + YourIPAddress + "/";
String METHOD_NAME = getMethodName(serviceMethod);
String SOAP_ACTION = NAMESPACE + METHOD_NAME;
String URL = "http://" + YourIP + "/YourService.asmx";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("sPassword", sYourPassword);
request.addProperty("sData", sServerDB);
request.addProperty("sSP_Name", storedProc);
request.addProperty("sParam", params);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Enable the below property if consuming .Net service
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
numberOfBytesTransmitted = numberOfBytesTransmitted + StringToBytes(request.toString());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
SoapPrimitive returnable = null;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
returnable = (SoapPrimitive)envelope.getResponse();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Msg:" + e.getMessage() + "; SP:" + storedProc + "; Params: " + params + "; Method:" + METHOD_NAME);
}
return returnable;
}

org.xmlpull.v1.xmlpullparserexception expected start_tag error when using ksoap2

I use ksoap2 to connect .NET by web service.
This is my Dataset
public DataSet getphimall()
{
DataSet ds1 = new DataSet();
try
{
SqlConnection cnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMHAUI;Integrated Security=True");
SqlCommand cmd = new SqlCommand("sp_GetAllSemester_ad", cnn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds1);
return ds1;
}
catch (Exception e)
{
return null;
}
}
And this is my webservice
[WebMethod]
public DataSet getSM()
{
Class1 phim1 = new Class1();
return phim1.getphimall();
}
And this is my javaconnector class
public class getSM {
String tenphim;
String daodien;
private static final String SOAP_ACTION = "http://tempuri.org/getSM";
private static final String METHOD_NAME = "getSM";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:50532/wsAndroid.asmx";
public getSM getallphim()
{
SoapObject table = null;
SoapObject client = null;
SoapObject tableRow = null;
SoapObject responseBody = null;
AndroidHttpTransport transport = null;
SoapSerializationEnvelope sse = null;
//cái này trong tut viết thế, mình lười đổi tên
sse = new SoapSerializationEnvelope(SoapEnvelope.VER11);
sse.addMapping(NAMESPACE, "getSM", this.getClass());
sse.dotNet = true;
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
getSM setphim = new getSM();
try
{
client = new SoapObject(NAMESPACE, METHOD_NAME);
sse.setOutputSoapObject(client);
sse.bodyOut = client;
androidHttpTransport.call(SOAP_ACTION, sse);
responseBody = (SoapObject) sse.getResponse();
responseBody = (SoapObject) responseBody.getProperty(1);
table = (SoapObject) responseBody.getProperty(0);
tableRow = (SoapObject) table.getProperty(0);
setphim.daodien = tableRow.getProperty("ID").toString();
setphim.tenphim = tableRow.getProperty("SemesterName").toString();
return setphim;
} catch (Exception e)
{
setphim.daodien = e.toString();
setphim.tenphim = e.toString();
return setphim;
}
}}
But When I run my emulator, I have an error
org.xmlpull.v1.xmlpullparserexception expected start_tag error
Please help me! Thanks
There might be a few reasons for the exception that you are getting.
Wrong Parameters for the SOAP call : try to confirm if the values of NAMESPACE, ACTION, METHOD and URL are correct or not, by looking at the WSDL file
Invalid response from server : try to log the response that the server sends to you and check if you are getting correct well-structured XML or not
androidHttpTransport.debug = true;
//execute request
androidHttpTransport.responseDump; //response string from server
dotNet attribute of the envelope : try using soapEnvelope.dotNet=true

kSoap, when I get my parameters on my webservice their values are null, why?

I'm trying to make a webservice in Java (Tomcat) and I'm calling it from Android with kSoap. The parameters when my webService is called are null. I don't know why.
Data of my WebService
Punto Final Información
Nombre de Servicio\: {http://serv.trivial.com/}UsuariosWebServiceImplService
Nombre de Puerto\: {http://serv.trivial.com/}UsuariosWebServiceImplPort
Dirección\: .../UsuariosWebService/usuarios
Clase de Implantación\: com.trivial.serv.UsuariosWebServiceImpl
And my code is:
private void registroServidor(String usuario, String regId)
{
//http://localhost:8080/UsuariosWebService/usuarios?wsdl
final String NAMESPACE = "http://serv.trivial.com/"; //Buscar namespace en el wsdl
final String URL="http://10.0.2.2:8080/UsuariosWebService/usuarios";
final String METHOD_NAME = "createUser";
//final String SOAP_ACTION = "http://serv.trivial.com/createUser";
final String SOAP_ACTION = "";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("usuario", usuario);
request.addProperty("regGCM", regId);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.doNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try
{
transporte.call(SOAP_ACTION, envelope);
SoapPrimitive resultado_xml =(SoapPrimitive)envelope.getResponse();
String res = resultado_xml.toString();
if(res.equals("true"))
Log.d("GCMTest", "Registro WS: OK.");
}
catch (Exception e)
{
System.out.println("EXCEPTION!!!!!!" + e);
e.printStackTrace();
Log.d("GCMTest", "Registro WS: NOK. " + e.getCause() + " || " + e.getMessage());
}
}
My WebService:
#Override
#WebMethod
public boolean createUser(#QueryParam("usuario") String usuario,#QueryParam("regGCM") String regGCM) {
System.out.println("2222");
boolean result = false;
UsuarioDTO dto = new UsuarioDTO();
//!!!!!! regGCM and usuario are null!!!!!!
dto = new UsuarioDTO(regGCM, usuario);
if (dao.findUserByUsuario(usuario) != null){
result = dao.update(dto);
}else{
result = dao.insert(dto);
}
System.out.println("New User info: " + dto.toString());
return result;
}
#WebMethod
public abstract boolean createUser(#QueryParam("usuario") String usuario,#QueryParam("regGCM") String regGCM);
Personally I've successfully used ksoap to connect to a .NET web service, so I am not sure what your parameter names should look like when using Tomcat. I have noticed however that you do not specify the data type for your parameters - could this be the problem? Here's an example:
// ## init request parameters
PropertyInfo pi = new PropertyInfo();
// ## usuario
pi.setName("usuario");
pi.setValue(usuario);
pi.setType(String.class);
request.addProperty(pi);

Retrieve password from mysql database is send to email in android+ java webservices

I have developed login form android application. Here I have to implement the forget password field. If I click on that forget password textview then it will go to next activity.
The next activity will take email from user and check its validation from mysql database which is calling soap webservices.
I have done the above part.
Now i have to implement below part:
The email is valid means fetch the password from mysql database and send these password to valid email.
How can I implement this part in my java webservice code.please help me.give me some solution.
This is my java webservice code for check the email is valid or invalid:
public class Checkemail {
public String authentication(String Email){
String retrievedUserName = "";
String status = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE email = '"+Email+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("email");
}
if(retrievedUserName.equals(Email)){
status = "Valid Email";
}
else{
status = "Invalid Email!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
}
This is my android code:
public class Login extends Activity {
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://10.0.0.75:8080/XcartLogin/services/Checkemail?wsdl";
private final String SOAP_ACTION = "http://xcart.com/authentication";
private final String METHOD_NAME = "authentication";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText Email = (EditText) findViewById(R.id.tf_userName);
String email = Email.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("Email");//Define the variable name in the web service method
unameProp.setValue(email);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String status = response.toString();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
}
catch(Exception e){
}
}
}
How can I implement fetch the password is sent to email in java webservice code?
Use by this code , its help for you...
String email_id = etxt_user.getText().toString();
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Email", email_id);
Pattern EMAIL_ADDRESS_PATTERN =Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+");
Matcher matcher = EMAIL_ADDRESS_PATTERN.matcher(email_id);
if(matcher.matches()){
Log.v(TAG, "Your email id is valid ="+email_id);
// System.out.println("Your email id is valid ="+email);
}
else{
// System.out.println("enter valid email id");
Log.v(TAG, "enter valid email id" );
}
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE aht = new HttpTransportSE(URL);
try {
aht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
aht.call(SOAP_ACTION, soapEnvelope);
SoapObject resultsRequestSOAP = (SoapObject) soapEnvelope.bodyIn;
Log.v("TAG", String.valueOf(resultsRequestSOAP));
} catch (Exception e) {
e.printStackTrace();
}
}
Use this code.. its very helpful to you.....
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Connect extends Activity {
static StringBuilder sb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String strURL = "http://hostserver/";
final String username = "username";
final String password = "password";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication
(username, password.toCharArray());
System.out.println(pa.getUserName() + ":" + new
String(pa.getPassword()));
return pa;
}
});
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("Exception");
}
}
Log.d("DATA", sb.toString());
}
}

Ksoap2 Android adding Attributes to a simple property

I am trying to create a new property inside a SoapObject that will contain simple string properties with attributes to them like this:
<Power Unit="kw">1500</Power>
here is the code i am using for my samples below.
final SoapObject powerObject= new SoapObject(namespace, "Power");
powerObject.addAttribute("Unit", getPowerUnit());
PropertyInfo powerObjectProperty = new PropertyInfo();
powerObjectProperty .setName("");
powerObjectProperty .type = String.class;
powerObjectProperty .setValue(getPower());
powerObjectProperty .addProperty(powerObjectProperty);
root.addSoapObject(powerObject); // this is my root for the hierarchy
The best that i could reach is the following:
<Power Unit="kw"><>1500</></Power>
i even tried to add everything as a string but that encodes the <> tags.
&ltPower Unit"kw"&gt1500&lt/Power&gt
I am using:
ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar on android.
Ok i have solved this issue, here is how:
I have created a new soap object called TextSoapObject
public class TextSoapObject extends SoapObject {
public static final String TAG = TextSoapObject.class.getSimpleName();
public TextSoapObject(String namespace, String name) {
super(namespace, name);
}
public String text;
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
Next i overrided SoapSerialization envelope like this:
public class ValueSerializationEnvelope extends SoapSerializationEnvelope {
public ValueSerializationEnvelope(int version) {
super(version);
}
public static final String TAG = ValueSerializationEnvelope.class.getSimpleName();
#Override
public void writeObjectBody(XmlSerializer writer, KvmSerializable obj) throws IOException {
if (obj instanceof TextSoapObject) {
writer.text(((TextSoapObject) obj).getText());
}
super.writeObjectBody(writer, obj);
}
}
And that's it.
To use this you would do the following:
final TextSoapObject costOfRepairs = new TextSoapObject(namespace, "CostOfRepairs");
costOfRepairs.addAttribute("Currency", getCurrency());
costOfRepairs.setText(getRepairCosts() + "");
root.addSoapObject(costOfRepairs);
EDIT:
This issue has been recognized for the ksoap2 library and addressed here:
http://code.google.com/p/ksoap2-android/issues/detail?id=112
Should be fixed in the next ksoap2 Release.
Try the following code
SoapObject soOriginDestInfo = new SoapObject(namespace_ns, "OriginDestinationInformation");
SoapPrimitive spDeptDtTm = new SoapPrimitive(namespace_ns, "DepartureDateTime", "asdadsad");
spDeptDtTm.addAttribute("Unit", "kw");
soOriginDestInfo.addProperty("DepartureDateTime", spDeptDtTm);
request.addSoapObject(soOriginDestInfo);
You can add property in your soap object and pass any value you want.
SoapObject request = new SoapObject(NAMESPACE, NAME);
request.addProperty("powerInKw", 1500);
like a key value pair.
I'm consuming some .NET web services and need to addAttribute to an addProperty while using ksoap for this xml:
<Element FirstAttribute="int" SecondAttribute="double" />
Here's what I did (including some extra help looping and passing in a double) to pass in this request:
String xml = null;
final String NAMESPACE = "http://yournamespace.org/";
final String SOAP_ACTION = "http://yournamespace.org/NameOfYourOperation";
final String METHOD_NAME = "NameOfYourOperation";
final String URL = "http://whereyourserviceis.com/Service.asmx";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
for (int i=0; i < anArray.size(); i++)
{
Some_obj obj = anArray.get(i);
SoapObject attributes = new SoapObject(NAMESPACE, "Element");
int a = Integer.parseInt(obj.someIntString);
attributes.addAttribute("FirstAttribute", a);
Double v = Double.parseDouble(obj.someDoubleString);
attributes.addAttribute("Value", v);
request.addProperty("SecondAttribute", attributes);
//request.addSoapObject(request);
Log.d(TAG,"=======obj.someIntString======: " + a + "=======obj.someDoubleString========: " + v);
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
MarshalFloat md = new MarshalFloat();
md.register(envelope);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
try
{
HttpTransportSE transport = new HttpTransportSE(URL, 60000);
transport.debug = true;
transport.call(SOAP_ACTION, envelope);
xml = transport.responseDump.toString();
Log.d(TAG, "getUpdates===============" + xml);
}
catch(SocketException ex)
{
Log.e("SocketException : " , "Error on getUpdates() " + ex.getMessage());
}
catch (Exception e)
{
Log.e("Exception : " , "Error on getUpdates() " + e.getMessage());
}
Take note of the MarshalFloat part...this is there if you're passing in a double value so the soap can serialize properly.

Categories

Resources