Android ksoap2 WCF wsHttpBinding - android

I am trying to connect my android application to WCF web service (IIS 6),with
basicHttpBinding everything works OK, but i want it to be more secure so i set the
WCF binding to wsHttpBinding, i understed this is a littele bit tricky on ksoap2,
i am getting an error:
Code: s:Sender, Reason: The message could not be processed.
This is most likely because the action 'http://tempuri.org/IService1/HelloWorld'
is incorrect or because the message contains an invalid or expired security context token or
because there is a mismatch between bindings.
The security context token would be invalid if the service aborted the channel due to inactivity.
To prevent the service from aborting idle sessions prematurely increase the Receive timeout
on the service endpoint's binding.
Here is my code (android)
Element e = new Element();
e.setName("To");
e.setNamespace("http://www.w3.org/2005/08/addressing");
e.addChild(Node.TEXT,
URL);
Element e1 = new Element();
e1.setName("Action");
e1.setNamespace("http://www.w3.org/2005/08/addressing");
e1.addChild(Node.TEXT,
"http://tempuri.org/IService1/HelloWorld");
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
//envelope.implicitTypes = true;
envelope.dotNet = true;
//envelope.headerOut =new Element[] { e, e1 };
envelope.headerOut = buildHeader(URL, SOAP_ACTION);
envelope.setOutputSoapObject(Request); // prepare request
try {
// androidHttpTransport.call(SOAP_ACTION, envelope);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
String resultData=result.getProperty(0).toString();
//Object result = envelope.getResponse();
//SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
//String resultData = result.toString();
//msg = resultData;
} catch (IOException | XmlPullParserException ex) {
ex.printStackTrace();
msg = ex.getMessage();
}
i all so try:
private static Element[] buildHeader(String url, String soapAction) {
String HTTP_ADDRESSING_ANONYMOUS = "http://www.w3.org/2005/08/addressing/anonymous";
String HTTP_ADDRESSING = "http://www.w3.org/2005/08/addressing";
String ACTION = "Action";
String TO = "To";
String ADDRESS = "Address";
String REPLY_TO = "ReplyTo";
String MUST_UNDERSTAND = "mustUnderstand";
List<Element> headers = new ArrayList<Element>();
Element elementAction = new Element().createElement(HTTP_ADDRESSING, ACTION);
elementAction.addChild(Node.TEXT, soapAction);
elementAction.setAttribute(HTTP_ADDRESSING, MUST_UNDERSTAND, "1");
headers.add(elementAction);
Element elementTo = new Element().createElement(HTTP_ADDRESSING, TO);
elementTo.addChild(Node.TEXT, url);////////////////////////////
elementTo.setAttribute(HTTP_ADDRESSING, MUST_UNDERSTAND, "1");
headers.add(elementTo);
Element elementReplyto = new Element().createElement(HTTP_ADDRESSING, REPLY_TO);
Element address = new Element().createElement(HTTP_ADDRESSING, ADDRESS);
elementReplyto.addChild(Node.ELEMENT, address);
address.addChild(Node.TEXT, HTTP_ADDRESSING_ANONYMOUS);
elementReplyto.setAttribute(HTTP_ADDRESSING, MUST_UNDERSTAND, "1");
headers.add(elementReplyto);
int size = headers.size();
Element[] array = new Element[size];
for (int i = 0; i < size; i++) {
array[i] = headers.get(i);
}
return array;
}
can someone Help

Related

getting error while calling soap request in android?

I am using Ksoap2 android assembly 2.4 in my android application.I am try to call the web service by using soap.But I am getting the error at transport.call(soapAction, envelop); this line.
LOGCaT:
org.xmlpull.v1.XmlPullParserException: expected: END_TAG {http://schemas.xmlsoap.org/soap/envelope/}Body (position:END_TAG </{http://schemas.xmlsoap.org/soap/envelope/}soap:Fault>#1:301 in java.io.InputStreamReader#41743310)
And Here my code is:
String url = "http://192.168.56.1:8080/CxfWebservice/webservices/Calculator";
// String namespace = "http://localhost:8080/wsdl";
String namespace = "http://192.160.59.1:8080/wsdl";
String methodname = "sum";
public static void SoapOperation(String url, String method_name,
String name_space) throws Exception {
String soapAction = name_space + method_name;
SoapObject request = new SoapObject(name_space, method_name);
PropertyInfo p = new PropertyInfo();
p.setName("arg0");
p.setValue(5);
p.setType(Integer.TYPE);
PropertyInfo p1 = new PropertyInfo();
p1.setName("arg1");
p1.setValue(15);
p1.setType(Integer.TYPE);
request.addProperty(p );
request.addProperty(p1);
SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelop.setOutputSoapObject(request);
envelop.dotNet = true;
HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;
transport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
transport.call(soapAction, envelop);
String xml = transport.responseDump;
System.out.println("the response xml is:"+xml);
}
above is my code with please give me a solution for this.
Here is an example. Use this code
public void InteractWithWebService() {
try {
final String URL = con.getResources().getString(R.string.URL);
final String NameSpace = con.getResources().getString(
R.string.NAMESPACE);
final String MethodName = "sum";
final String SOAP_ACTION = con.getResources().getString(
R.string.SOAP_ACTION)
+ MethodName;
SoapObject Request = new SoapObject(NameSpace, MethodName);
Request.addProperty("param_name", Object_name.getText().toString()
.trim());
Request.addProperty("param_name", Object_name.getText().toString()
.trim());
SoapSerializationEnvelope soapEnvelop;
soapEnvelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelop.dotNet = true;
soapEnvelop.setOutputSoapObject(Request);
HttpTransportSE htp = new HttpTransportSE(URL);
htp.call(SOAP_ACTION, soapEnvelop);
// SoapObject response;
SoapPrimitive resultString = (SoapPrimitive) soapEnvelop
.getResponse();
if (resultString != null) {
status = Integer.parseInt(resultString.toString());
}
} catch (Exception ex) {
status = -1;
}
}
Add these lines in your strings file
<string name="NAMESPACE">http://tempuri.org/</string>
<string name="URL">http://Your_Localhost_address/Name_of_Service.svc</string>
<string name="SOAP_ACTION">http://tempuri.org/IName_of_Service/</string>

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

error that occurs while the data from the webservice Ksoap

error occurs when requesting data from the internet in ksoap object
public String[] getProfile(String email) {
String[] profileArray = new String[3];
METHOD_NAME = "getProfile";
SoapObject getprofileSoapObject = new SoapObject(NAMESPACE,METHOD_NAME);
//To avoid code duplication getproperty. Set info
getprofileSoapObject.addProperty(setProperty("email", email));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(getprofileSoapObject);
HttpTransportSE http = new HttpTransportSE(URL);
try { //call httptransport
http.call(SOAP_ACTION, envelope);
SoapObject SoapObject2 = (SoapObject) envelope.bodyIn;
//Set profile detail
profileArray[0] = SoapObject2.getProperty(0).toString();
profileArray[1] = SoapObject2.getProperty(1).toString();
profileArray[2] = SoapObject2.getProperty(2).toString();
return profileArray;
} catch (Exception e) {
//System.out.println(e.getMessage());
}
return profileArray;
}
NullPointerException error occurs after http.call

How to send DateTime to .net webService from android (ksoap2)?

I've a .net webservice, where I have to send a param (type of dateTime), as You can see:
<startDateTime>dateTime</startDateTime>
In Android client, I use ksoap2, and I don't know , How to send that type of data?
Please help with setting this type - code below not works.
PropertyInfo propInfo3 = new PropertyInfo();
propInfo3.name="startDateTime";
propInfo3.value="2012-02-01";
Here is how I call web service methods in my application. Note the method I used to convert java dates. You require an ISO date format.
protected static Object callMethod(String method, Map<String, Object> parameters) throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, method);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();
envelope.setOutputSoapObject(request);
if (parameters != null) {
for (String item : parameters.keySet()) {
Object itemValue = parameters.get(item);
if (itemValue.getClass().getName().equals("java.util.Date")) {
// If it's a date then we have to format it because ksoap
// does not know how to do this.
request.addProperty(item, getSOAPDateString((java.util.Date) itemValue));
} else {
request.addProperty(item, itemValue);
}
}
}
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS, 10000);
httpTransport.debug = true;
httpTransport.call(WSDL_TARGET_NAMESPACE + "/" + method, envelope);
String soapString = httpTransport.requestDump;
System.out.println(soapString);
return envelope.getResponse();
}
Here is the method that returns the actual string:
private static Object getSOAPDateString(java.util.Date itemValue) {
String lFormatTemplate = "yyyy-MM-dd'T'hh:mm:ss'Z'";
DateFormat lDateFormat = new SimpleDateFormat(lFormatTemplate);
String lDate = lDateFormat.format(itemValue);
return lDate;
}
In your server, what's the return from the client?
When I have a problem like this, I show in the Logcat on Android what I'm sending and in the server side what I'm getting.
I had a little problem with date too (I'm using ksoap2 and webservices), I solve my problem sending the date in the util.Date, then I use SimpleDateFormat with a pattern date in my project and convert that string to what I want.
cya,
Bertan
Here is my code that sends to the WS:
public static byte[] send(String... param) throws SocketTimeoutException, IOException, XmlPullParserException, Exception{
//First I send the WS Name
String ws = param[0];
//Second is the operationName
SoapObject soap = new SoapObject(URL_SOAP, param[1]);
Object retorno = null;
int tamParam = param.length;
//The 3 parameter for the infinity its the properties, name and the next it's the value...
if (tamParam > 0) {
for (int i = 2; i < tamParam; i++) {
soap.addProperty(param[i], param[++i]);
}
}
// create a envelope for the soap object
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(soap);
// create a HttpTransport to send the object soap with 15s delay
MyHttpTransport httpTransport = new MyHttpTransport(URL + ws, 15000);
// send the req
Long tempo1 = 0l;
tempo1 = System.currentTimeMillis();
httpTransport.call("", envelope);
retorno = envelope.getResponse();
Long tempo2 = System.currentTimeMillis();
httpTransport.reset();
//I ever get byte[] from the WS...
if (retorno != null) {
byte[] bloc = Base64.decode(retorno.toString(), Base64.DEFAULT);
return bloc;
} else {
return null;
}
}

How to parse a SoapObject in android

I'm using webservices for an application to get the data from external servers. I'm able to connect to the server, send my SOAP request and able get the data back to my android class as SoapObject.
Here I'm having trouble parsing this SoapObject to retrieve the values (as strings) coming from the webservice.
My code is here:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
mInflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
System.out.println("Entered "+getClass().getSimpleName());
//Calling the web service to get the documents list
callService("getDocumentsList","http://wservice.friedmaggy.com/getDocumentsList");
-- I have created callService method to call the webservice.:
public void callService(String operation, String soapaction)
{
try {
String SOAP_ACTION = soapaction;
String OPERATION_NAME = operation;
String WSDL_TARGET_NAMESPACE = getString(R.string.targetNamespace);
String SOAP_ADDRESS = getString(R.string.soapAddress);
SoapObject request = new SoapObject(
WSDL_TARGET_NAMESPACE, OPERATION_NAME);
System.out.println("SOAP_ACTION "+SOAP_ACTION);
System.out.println("OPERATION_NAME "+OPERATION_NAME);
System.out.println("WSDL_TARGET_NAMESPACE "+WSDL_TARGET_NAMESPACE);
System.out.println("SOAP_ADDRESS "+SOAP_ADDRESS);
// System.out.println("SOAP_ACTION "+SOAP_ACTION);
PropertyInfo propInfo = new PropertyInfo();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
HttpTransportSE httpTransport = new HttpTransportSE(
SOAP_ADDRESS);
envelope.setOutputSoapObject(request);
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response.getPropertyCount()>0){
data=new StringBuilder();
for (int i = 0; i < response.getPropertyCount(); i++) {
Course c = new Course((SoapObject) response.getProperty(i));
courseList.add(c);
}
for (Course c : courseList) {
data.append("CourseName :" + c.getName());
results.add(c.getName());
}
-- As seen above, i'm passing the whole response object to another bean class to fetch the values.(Course c = new Course((SoapObject) response.getProperty(i));)
Can you help me how to parse this response object to fetch the required String values out.?
androidHttpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
Vector<SoapObject> res= null;
if (response instanceof SoapObject) {
res = new Vector();
res.add((SoapObject) response);
} else if (response instanceof Vector) {
res = (Vector<SoapObject>) response;
}
for(SoapObject so1: res){
//retrieve String here from soap object using this
so1.getProperty(0).toString();
//then so1.getProperty(1).toString and likewise
}

Categories

Resources