How to send SOAP request Android - 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]);
}
}
}

Related

Response from SOAP webservice always returns null Android studio

Im trying to get some response from several SOAP webservices at last i tried to run a code that is a well very known example on the internet. But i realized that even this doesnt run on my project. I hardly tried to understand what the error could be but i dont know why its not working with soap.
I would really appriacate your help.
Downloaded new version of KSOAP2 and also permission for internet is given.
public class WEBSERVİCE extends AppCompatActivity {
Button btn;
EditText et;
TextView txv;
String celcius="21";
String fahren;
private String NAMESPACE = "https://www.w3schools.com/xml/";
private String METHOD_NAME = "CelsiusToFahrenheit";
private String SOAP_ACTİON = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
private String URL = "https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit?WSDL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
txv = findViewById(R.id.textView);
et = findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
txv.setText("calculating");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... objects) {
return getBolum(celcius);
}
#Override
protected void onPostExecute(String o) {
txv.setText(fahren + "F");
super.onPostExecute(o);
}
}
public String getBolum(String celsius) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("Celcius");
pi.setValue(celsius);
pi.setType(double.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHTTPTransport = new HttpTransportSE(URL);
try {
androidHTTPTransport.call(SOAP_ACTİON, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
fahren = response.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return fahren;
}
}
No Error Messages but the value it turns back is always "null"
EDIT:posted changed code again
There isn't anything wrong with SOAP Api. The problem is your AsyncTask class. Read the documentation for AsyncTask first. Please do proper research before you use any code from internet. Always read about the components that are used snippets on internet otherwise you are going to have hard time figuring out problems.
Your AsyncTask class is declared as:
private class AsyncCallWS extends AsyncTask<String,Void,Void>
Change it to
private class AsyncCallWS extends AsyncTask<String,Void,String>
Third generic parameter in your Void which is supposed to be result type. So in your case your async task won't return any data once it is finished.
//CHANGE TYPE TO STRING
public String getBolum(String celsius) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("Celcius");
pi.setValue(celsius);
pi.setType(double.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHTTPTransport = new HttpTransportSE(URL);
try {
androidHTTPTransport.call(SOAP_ACTİON, envelope);
SoapPrimitive response= (SoapPrimitive) envelope.getResponse();
//RETURN RESULT
return response.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
//I forgot this line previously:
return "";
}}
In your async task, you need to change return type of doInBackground and paramter of onPostExecute to String:
#Override
protected String doInBackground(String... objects) {
return getBolum(celcius); //RETURN RESULT
}
#Override
protected void onPostExecute(String result) {
txv.setText(result+"F");
fahren = result;
super.onPostExecute(result);
}
It should work now.

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.

Android, Read timed auto and soap

Ksoap2 trying to connect to the web service. However, the "read timed out" error getting. I do not know what to do.
Ksoap2 'There is an error too? where is the error
Ksoaps libs version: 3.0.1
Emulator 2.2
MainActivity.java
public class MainActivity extends Activity {
static final String METHOD_NAME = "GetTableUpdateVersionByTableName";
static final String NAMESPACE = "http://tempuri.org/";
static final String URL = "https://app.xxx.com/IntSecureFlight/SFInternal.svc";
static final String DOMAIN = "app.xxx.com";
static final String SOAP_ACTION = "http://tempuri.org/IOperationSvc/GetTableUpdateVersionByTableName";
TextView sonuc;
EditText tableName;
String message;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sonuc = (TextView) findViewById(R.id.textView1);
tableName = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), tableName.getText(),
Toast.LENGTH_LONG).show();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// uzun islem oncesi yapilacaklar
}
#Override
protected String doInBackground(String... strings) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("tableName", tableName.getText().toString());
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
soapEnvelope.headerOut = new Element[1];
soapEnvelope.headerOut[0] = buildAuthHeader();
try {
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 2000);
transportSE.call(SOAP_ACTION, soapEnvelope);
Object result = soapEnvelope.getResponse();
if (result instanceof SoapFault12) {
SoapFault12 soapResult = (SoapFault12) result;
message = soapResult.getLocalizedMessage();
} else if (result instanceof SoapObject) {
SoapObject soapResult = (SoapObject) result;
message = soapResult.getProperty(0).toString();
}
} catch (SoapFault12 e) {
message = e.getMessage();
} catch (XmlPullParserException e) {
message = e.getMessage();
} catch (Exception e) {
message = e.getMessage();
}
return message;
}
#Override
protected void onPostExecute(String result) {
sonuc.setText(message);
super.onPostExecute(result);
}
}
public Element buildAuthHeader() {
Element h = new Element().createElement(NAMESPACE, "UsernameToken");
Element username = new Element().createElement(NAMESPACE, "Username");
username.addChild(Node.TEXT, "genel");
h.addChild(Node.ELEMENT, username);
Element pass = new Element().createElement(NAMESPACE, "KurumKod");
pass.addChild(Node.TEXT, "050");
h.addChild(Node.ELEMENT, pass);
return h;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
HttpTransportSEImpl
public class HttpTransportSEImpl extends HttpTransportSE {
public HttpTransportSEImpl(String url) {
super(url);
}
#Override
public ServiceConnection getServiceConnection() throws IOException {
ServiceConnection connection = super.getServiceConnection();
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
return connection;
}
}
AndroidManifest add <uses-permission android:name="android.permission.INTERNET"/>
read timed out error and socket time out errors will come on low internet connections
check your internet connection strength
or check the server response string, you may mismatch the data-type on reading.
and add permissions to listen network_state and
access_fine_location
edit your code:
HttpsTransportSE transportSE = new HttpsTransportSE(DOMAIN,
443, "/IntSecureFlight/SFInternal.svc", 60000);

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;
}

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