How to cancel current ksoap2 HttpTransportSE call? - android

I have following code:
public class DoTask extends AsyncTask<Object, Object, Object> {
private HttpTransportSE mHttpTransportSE;
public DoTask() {
}
public void cancelTask(){
System.out.println("cancelling task 1");
if(mHttpTransportSE != null){
System.out.println("cancelling task 2");
mHttpTransportSE.reset();
try {
System.out.println("cancelling task 3");
mHttpTransportSE.getServiceConnection().disconnect();
cancel(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Object itemImage) {
}
#Override
protected Object doInBackground(Object... arg0) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = getSoapSerializationEnvelope(request);
mHttpTransportSE = getHttpTransportSE();
mHttpTransportSE.call(SOAP_ACTION, envelope);
mSuccess = true;
}
catch (Exception e){
System.out.println("other exception");
e.printStackTrace();
mSuccess = false;
mErrorMessage = "ERROR!";
}
return null;
}
private final SoapSerializationEnvelope getSoapSerializationEnvelope(SoapObject request) {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
envelope.setOutputSoapObject(request);
return envelope;
}
private final HttpTransportSE getHttpTransportSE() {
HttpTransportSE ht = new HttpTransportSE(Proxy.NO_PROXY, MAIN_REQUEST_URL, 60000);
ht.debug = true;
ht.setXmlVersionTag("<!--?xml version=\"1.0\" encoding= \"UTF-8\" ?-->");
return ht;
}
private String getValue(String value){
if(value == null || value.equals("anyType{}"))
return "";
return value;
}
}
I want to cancel the call when user clicks something. Tried to cancel it by using the method of cancelTask() called in my activity but I still can get the error message of catch (because the server is down right now, so it can't reach the server).
How can I cancel the ksoap call?

Related

How to send SOAP request Android

I'm using ksoap to make request.
But, I'm having doubts on how to send header and below format in soap request.
I'm having soap request data, I want to send soap request to server:
Soap Request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ihc="http://testingsite.com" xmlns:ihcl="http://testingsite.com">
<soapenv:Header>
<wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext">
<wsse:UsernameToken>
<wsse:Username>name</wsse:Username>
<wsse:Password>password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<MyList xmlns="http://testingsite.com">
<Details>
<Name1>hi</Name1>
<Name2>Hello</Name2>
<MyAddress>
<Address1 IsPrimary="Y">
<Add1>Personal</Add1>
<Add2>Personal</Add2>
</Address1>
</MyAddress>
</Details>
</MyList>
</soapenv:Body>
</soapenv:Envelope>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.test);
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
#Override
protected String doInBackground(String... params) {
publishProgress("Loading contents...");
try {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject request = new SoapObject(NAMESPACE, METHOD);
PropertyInfo quotesProperty = new PropertyInfo();
request.addProperty("WsClientName","RAKDEDTester");
request.addProperty("Password", "d41d8cd98f00b204e9800998ecf8427e");
envelope.bodyOut = request;
HttpTransportSE transport = new HttpTransportSE(URL);
try {
transport.call(NAMESPACE + SOAP_ACTION_PREFIX + METHOD, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
if (envelope.bodyIn != null) {
SoapPrimitive resultSOAP = (SoapPrimitive) ((SoapObject) envelope.bodyIn).getProperty(0);
resp=resultSOAP.toString();
}
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
textView.setText(text[0]);
}
}
}

Can't post data using KSoap2 on local server

I have a .net Api to send data on the server.I am using KSoap2 to post that data But fail to do .I am using the code
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new backMethod().execute(); // This is an important Step
}
public class backMethod extends AsyncTask<String, Object, Object > {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Checking...");
this.dialog.show();
}
#Override
protected void onPostExecute(Object result) {
//Here All your UI part is Done
if (result != null) {
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setTag(result);
} else {
Toast.makeText(getApplicationContext(),
"Result Found is == " + result + "", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected Object doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
response = (SoapObject) envelope.getResponse();
//here SoapPrimitive is an important part
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
while debugging flow of code automatically move to catch block and give the exception network not found.

result of web service?

i wrote a code using SOAP function to get from web service , the problem is that the response is not an xml string , what i need to know , the error from my android code SOAP function ? or from web service ?
why the result is liske this
public String SOAP_ACTION2 = "http://tempuri.org/GetDataTable";
public String OPERATION_NAME2 = "GetDataTable";
public String SOAP_ADDRESS2 = "http://192.168.0.15/EServicedesk/DesktopModules/EServiceDesk.Website/ESDWebService/Auth.asmx?WSDL";
Object response;
String XMLData = null;
SoapSerializationEnvelope envelope;
SoapRequestTask2 task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
task = new SoapRequestTask2();
try {
XMLData = task.execute().get();
Log.i("task ", XMLData);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class SoapRequestTask2 extends AsyncTask<Void, Void, String> {
// runs on ui thread.
private String data;
protected void onPreExecute() {
}
// runs in the background thread. do not update ui from here
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME2);
PropertyInfo pi = new PropertyInfo();
pi.setName("UserID");
pi.setValue(193);
pi.setType(Integer.class);
request.addProperty(pi);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
response = null;
try {
// httpTransport.debug=true;
httpTransport.call(SOAP_ACTION2, envelope);
// String ss = httpTransport.requestDump;
response = envelope.getResponse();
data = response.toString();
// Log.i("respons", envelope.getResponse().toString());
} catch (Exception exception) {
response = exception.toString();
XMLData = response.toString();
}
return data;
}
here is the result :
task 2: anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; }; }; }; }; }; }; }; diffgram=anyType{DocumentElement=anyType{TargetTable=anyType{RequestHotList=MyRequests; Count=927; }; TargetTable=anyType{RequestHotList=MyAssignedRequests; Count=603; }; TargetTable=anyType{RequestHotList=MyServiceDeskRequests; Count=969; }; TargetTable=anyType{RequestHotList=MyWorkGroupRequests; Count=770; }; TargetTable=anyType{RequestHotList=MyApproval; Count=82; }; }; }; }
you can do something like this
Web service returns array of object
you can get value for each value for each object by going to perticular node then use getProperty() method to get value for required object as follow.
//old web services.
public void getLocation()
{
OPERATION_NAME = "GetLd";
SOAP_ACTION = Constants.strNAMESPACE+""+OPERATION_NAME;
REQUST_ID=3;
final Responce responce=new Responce();
Thread thread=new Thread(new Runnable()
{
SoapObject response;
#Override
public void run()
{
try
{
SoapObject request=new SoapObject(Constants.strNAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(Constants.strWEB_SERVICE_URL);
ht.call(SOAP_ACTION, envelope);
response = (SoapObject)envelope.bodyIn;
if(response!=null)
{
SoapObject str = null;
for(int i=0;i<response.getPropertyCount();i++)
str=(SoapObject) response.getProperty(i);
SoapObject str1 = (SoapObject) str.getProperty(0);
SoapObject str2 = null;
ArrayList<Location> arrData=new ArrayList<Location>();
for(int j=0;j<str1.getPropertyCount();j++)
{
str2 = (SoapObject) str1.getProperty(j);
Location location=new Location();
if(str2!=null)
{
responce.Result_Type=Constants.DataPresent;
if(isValidProperty(str2, "LocationName"))
{
location.setName(str2.getProperty("LocationName").toString());
}
if(isValidProperty(str2, "LocationId"))
{
location.setId(Integer.parseInt(str2.getProperty("LocationId").toString()));
}
arrData.add(location);
}
else
{
responce.Result_Type=Constants.NoDataPresent;
}
}
responce.ResponceData=arrData;
Log.d("Location", "------------------------");
for(int i=0;i<arrData.size();i++)
Log.d("Tag", arrData.get(i).toString());
}
}
catch (Exception e)
{
e.printStackTrace();
responce.Result_Type=Constants.Error;
}
finally
{
Message message=new Message();
message.what=REQUST_ID;
message.arg1=responce.Result_Type;
message.obj=responce;
handler.sendMessage(message);
}
}
});
thread.start();
}
boolean isValidProperty(SoapObject soapObject,String PropertyName)
{
if(soapObject!=null)
{
if(soapObject.hasProperty(PropertyName))
{
if(!soapObject.getProperty(PropertyName).toString().equalsIgnoreCase("")&&!soapObject.getProperty(PropertyName).toString().equalsIgnoreCase("anyType{}"))
return true;
else
return false;
}
return false;
}
else
return false;
}

Where Can I put IF statement for working?

I have some ksoap web service in timer action which is working every half an hour if I did it well. One of them send whole table rows to sql server and it turns me 0 or 1 depends on correctly sending. If it returns 1, it has to delete all row from sqlite.
Altough it returns 1, It does not get into if statements and does not work delete command.
I do not know my timer and thread is the right way for this and How can I do it correctly?
The Code:
try
{
final Timer V_Timer;
final Handler V_Handler;
V_Timer = new Timer();
V_Handler = new Handler(Looper.getMainLooper());
V_Timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
V_Handler.post(new Runnable()
{
public void run()
{
//for status update//
if(isConnected()){
Thread networkThread = new Thread() {
#Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_STATUS);
request.addProperty("MH_ID",hardwareID);
request.addProperty("Latitude",V_Latitude);
request.addProperty("Longitude",V_Longitude);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION_STATUS, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str_ = response.toString();
//final String str = response.toString()+"\n"+ V_Latitude +"\n"+V_Longitude;
runOnUiThread (new Runnable(){
public void run() {
Toast.makeText(MainActivity.this, str_, Toast.LENGTH_LONG).show();
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
//Insert Bulk//
if(isConnected()){
Thread networkThread2 = new Thread() {
#Override
public void run() {
str = "0";
try {
StringBuilder bulk = GetTotalRecord();
bulkinsert = bulk.toString();
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_BULK);
request.addProperty("Insert_Bulk",bulkinsert);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION_BULK, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
str = response.toString();
runOnUiThread (new Runnable(){
public void run() {
// Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
/////delete sqlite table/////
Log.d("str", str);
if (str=="1")
{
try {
dbobject.delete(SQLiteDB.TABLE_NAME_S, null, null);
Toast.makeText(MainActivity.this, "All Answers sent", Toast.LENGTH_LONG).show() ;
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity.this, "Error: Answers could not send \n "+e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
finally{
sqlitedb.close();
}
}
/////delete sqlite table/////
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread2.start();
//Insert Bulk end//
}
}
}});
}
},10000, 1000*60*30);
}
catch(Exception ex)
{
}
if (str=="1")
you can not compare String object this way in Java.
You should use equalsTo() or convert str to int
for instance:
if (str.equalsTo("1")) {
}
or
int strInt = Integer.parseInt( str )
if (strInt == 1) {
}

Android Soap Web service Error behind Proxy Server

I have written a program for communicating with a web service and get response value. But when i debug the programme i end with requestDump=null at the line androidHttpTransport.call(SOAP_ACTION, envelope); Can some one tell me the reason for the error and what can i do for this
public class WebService extends Activity {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
private final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private final String METHOD_NAME = "CelsiusToFahrenheit";
String celsius;
Button b;
TextView tv;
EditText et;
String res,resultval;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_service);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.Result);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//String result=getFarenheit(et.getText().toString());
//tv.setText(result+"°F");
new service().execute();
}
});
}
private class service extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... arg0) {
celsius=et.getText().toString();
SoapObject request= new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo celsuiusPI= new PropertyInfo();
celsuiusPI.setName("Celsius");
celsuiusPI.setValue(celsius);
celsuiusPI.setType(String.class);
request.addProperty("XMLMarks",celsuiusPI);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope (SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.implicitTypes = true;
envelope.enc = SoapSerializationEnvelope.ENC2003;
envelope.xsd = SoapEnvelope.XSD;
envelope.xsi = SoapEnvelope.XSI;
envelope.setOutputSoapObject(request);
envelope.setAddAdornments(false);
SoapPrimitive response;
HttpTransportSE androidHttpTransport=new HttpTransportSE(URL);
try{
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
String dump= androidHttpTransport.requestDump.toString();
response=(SoapPrimitive)envelope.getResponse();
Toast.makeText(WebService.this, response.toString(), 20).show();
Log.i("WebService output", response.toString());
System.out.println("WebService Response"+response.toString());
Object res= response.toString();
resultval=(String) res;
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
protected void onPostExecute(String h){
String result=h;
tv.setText(result+"°F");
}
}
}
Just replace your service AsyncTask with this new one and see result:
code:
private class service extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... arg0) {
System.out.println("In DoIn Background");
// Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Use this to add parameters
request.addProperty("Celsius", txtCel.getText().toString());
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
// this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
// Get the first property and change the label text
// txtFar.setText(result.getProperty(0).toString());
res = result.getProperty(0).toString();
} else {
Toast.makeText(getApplicationContext(), "No Response",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
protected void onPostExecute(String h) {
String result = h;
tv.setText(result + "°F");
}
}

Categories

Resources