How to send request post method in svc(soap) service in android? - android

I don't know how to send request in post method in soap service.Please someone help me to resolve this.
Here is my code so far.
//Code
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "Login";
String SOAP_ACTION = "http://tempuri.org/Login";
String URL = "http://hostname/AllServices.svc/Login";
protected void soap() {
// TODO Auto-generated method stub
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Set all input params
request.addProperty("sapcode", "3232323");
request.addProperty("password", "3232323");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
// Enable the below property if consuming .Net service
envelope.dotNet = true;
envelope.encodingStyle = SoapEnvelope.ENC;
envelope.setAddAdornments(false);
envelope.implicitTypes = false;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
Log.i("response", response.getProperty(0).toString());
// response.getProperty(0).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
private Element buildAuthHeader() {
Element h = new Element().createElement(NAMESPACE, "AuthHeader");
Element username = new Element().createElement(NAMESPACE, "User Name");
username.addChild(Node.TEXT, "tech");
h.addChild(Node.ELEMENT, username);
Element pass = new Element().createElement(NAMESPACE, "Password");
pass.addChild(Node.TEXT, "tech#001");
h.addChild(Node.ELEMENT, pass);
return h;
}
Basic Header Authentication:
Every method call from the API requires basic header authentication
User Name:
Password:
Method Type: POST
Return type is json format.

try {
// Build JSON string
JSONStringer loginCredentials = new JSONStringer().object()
.key("sapcode").value(userNameSend).key("password")
.value(passwordSend).endObject();
JSONObject jsonObj = new ServerResponse(
Urlgenerator.loginCheck()).getJSONObjectfromURL(
RequestType.POST, loginCredentials);
if (jsonObj != null) {
JSONObject loginObj = jsonObj.getJSONObject("Login");
if (loginObj != null) {
String errorcode = loginObj.getString("errorcode");
final String result = loginObj.getString("result");
if (errorcode.equalsIgnoreCase("0")) {
Utils.updateSharedPreference("remember", "true");
Utils.updateSharedPreference("sapcode",
userNameSend);
startActivity(new Intent(LoginScreen.this,
HomeScreen.class));
finish();
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
ToastUtils.displayToast(
ToastTypeEnum.ALERT_TOAST, result,
Toast.LENGTH_SHORT);
}
});
}
}
}
pDialog.dismiss();
} catch (Exception e) {
pDialog.dismiss();
}

Related

SocketTimeoutException: connect timed out Android ksoap

I´m using ksoap to connect toa webservice but I have a problem when I try to get a value from my webservice.
I got this error exception java.net.SocketTimeoutException: connect timed out
I already check the timeout solution and it still doesn´t work
Also I've already made sure that my METHOD,NAMESPACE and URL are correct according to my WSDL file.
Do you have any other solution?
Here is my code:
class SegundoPlano extends AsyncTask {
#Override
protected Void doInBackground(Void... voids) {
logeo();
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Re.compareTo("true") == 0) {
// try {
Intent I = new Intent(getApplicationContext(), Menu.class);
I.putExtra("folioen", Usuario);
startActivity(I);
// }
// catch (Exception ex)
//{
// Toast.makeText(MainActivity.this,ex.getMessage(), Toast.LENGTH_LONG);
// }
}
}
}
private String logeo() {
String mensaje;
String URL = "http://www.example.com/Servicios_web/WebService.asmx";
String metodo = "Acceso";
String namespace = "http://tempuri.org/";
String Accion = "http://tempuri.org/Access";
try {
SoapObject obtencion = new SoapObject(namespace, metodo);
obtencion.addProperty("usuario", User);
obtencion.addProperty("contra", Password);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(obtencion);
//HttpsTransportSE transporte = new KeepAliveHttpsTransportSE("192.168.4.38",440,"SERVIEPATH",7000);
HttpTransportSE transporte = new HttpTransportSE(URL, 100000);
transporte.call(Accion, soapEnvelope);
SoapPrimitive resultado = (SoapPrimitive) soapEnvelope.getResponse();
mensaje = resultado.toString();
Re = resultado.toString();
} catch (Exception ex) {
mensaje = ex.getMessage();
}
return mensaje;
}
Are you sure following is valid soap service URL?
String URL = "http://www.example.com/Servicios_web/WebService.asmx";
Do you have stack trace of where the call fails?

android - connect to web service

I'm try to connect android application to a web service uploaded on somee.
I have the following problem :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException
the web service code :
[WebService(Namespace = "http://www.n-m.somee.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
SqlConnection con = new SqlConnection(#"workstation id=WSDatabase.mssql.somee.com;packet size=4096;user id=***;pwd=***;data source=WSDatabase.mssql.somee.com;persist security info=False;initial catalog=WSDatabase ");
[WebMethod]
public string get_name(String pssw)
{
con.Open();
SqlCommand cmd = new SqlCommand("select username from users where pssw="+pssw, con);
string rd =(string) cmd.ExecuteScalar();
con.Close();
return rd;
}
}
I added the following line to manifest file:
** MainActivity.java file**
public class MainActivity extends AppCompatActivity {
protected String namespace="http://www.n-m.somee.com/";
protected String url="http://www.n-m.somee.com/WebService1.asmx";
protected String SOAPAction="http://www.n-m.somee.com/get_name";
protected String method_name= "get_name";
TextView user_name;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void goButton(View v)
{
user_name=(TextView)findViewById(R.id.textView1);
//allow internet
if(Build.VERSION.SDK_INT>9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//create soap object
SoapObject soapObject=new SoapObject(namespace,method_name);
soapObject.addProperty("pssw", "1234");
//create envelop
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
//Rrquest get data from webservice and set it into soapobject
HttpTransportSE transport = new HttpTransportSE(url);
try {
transport.call(SOAPAction, envelope);
// get data
SoapPrimitive output=(SoapPrimitive) envelope.getResponse();
//set data into control
user_name.setText("pssw: "+output.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
I appreciate any help
thank you
Your urls were a bit wrong. This is what I used,
protected String namespace = "http://www.nourhan-m.somee.com/";
protected String url = "http://www.nourhan-m.somee.com/WebService1.asmx";
protected String SOAPAction = "http://www.nourhan-m.somee.com/get_name";
protected String method_name = "get_name";
I made some modification to your code to make it work.
public String callService(String username) {
//create soap object and add params to it
SoapObject request = new SoapObject(namespace, method_name);
request.addProperty("pssw", username);
//create envelop
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
//set request to envelope
envelope.bodyOut = request;
HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;
try {
transport.call(SOAPAction, envelope);
Log.e("OUT", transport.requestDump);
return transport.responseDump;
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return "";
}
This is how I invoked the method,
You can invoke it as follows,
final String username = (TextView) findViewById(R.id.textView1)
new Thread(new Runnable() {
#Override
public void run() {
Log.e("OUT", callService(username));
}
}).start();
I got an empty response, maybe it's because I didn't give a valid username. Have a look at it. Cheers :)

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

provide security for header in ksoap2 in android

I want to call wsdl file in android using ksoap2 library. I have to provide security for header in soap envelope. I make below type of soap request which are as given below.
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<soap:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" soap:mustUnderstand="1">
<wsse:UsernameToken
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:Username>cbrown</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">welcome</wsse:Password></wsse:UsernameToken>
</wsse:Security>
</soap:Header>
<soap:Body xmlns:ns1="http://xmlns.oracle.com/bpel/aubi/mobile/Worklist">
<ns1:WorklistRetrievalREQ>
<ns1:WorklistType>HR_OFFER</ns1:WorklistType>
<ns1:Status>TODO</ns1:Status>
<ns1:Mode/>
</ns1:WorklistRetrievalREQ>
</soap:Body>
</soap:Envelope>
but I have no any idea that how to provide security in envelope header (). So, Please help for code.
Thanks in advance...
finally I got my answer of my question.
public class SOAP_WebService extends Activity
{
private final String NAMESPACE = "http://ws.simple/";
private final String URL = "http://10.0.2.2/SimpleWebservice/simple";
private final String SOAP_ACTION = "http://ws.simple/getString";
private final String METHOD_NAME = "getString";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.soap_webservice);
Button btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
callWebservice();
}
});
}
public void callWebservice()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo weightProp =new PropertyInfo();
weightProp.name = "arg0";
weightProp.setValue("rajan");
request.addProperty(weightProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// create header
Element[] header = new Element[1];
header[0] = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security");
header[0].setAttribute(null, "mustUnderstand","1");
Element usernametoken = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken");
usernametoken.setAttribute(null, "Id", "UsernameToken-1");
header[0].addChild(Node.ELEMENT,usernametoken);
Element username = new Element().createElement(null, "n0:Username");
username.addChild(Node.IGNORABLE_WHITESPACE,"CBROWN");
usernametoken.addChild(Node.ELEMENT,username);
Element pass = new Element().createElement(null,"n0:Password");
pass.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
pass.addChild(Node.TEXT, "welcome");
usernametoken.addChild(Node.ELEMENT, pass);
// add header to envelope
envelope.headerOut = header;
Log.i("header", "" + envelope.headerOut.toString());
envelope.dotNet = false;
envelope.bodyOut = request;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Log.i("bodyout", "" + envelope.bodyOut.toString());
try
{
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
}
catch (SoapFault e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
Log.d("Exception Generated", ""+e.getMessage());
}
}
}
This is Working for me... Try this.
public static Element buildAuthHeader() {
Element headers[] = new Element[1];
headers[0]= new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
headers[0].setAttribute(null, "mustUnderstand", "1");
Element security=headers[0];
//user token
Element usernametoken = new Element().createElement(security.getNamespace(), "UsernameToken");
usernametoken.setAttribute("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id", "UsernameToken-14CBAE357AC169AFA614664925178422");
//username
Element username = new Element().createElement(security.getNamespace(), "Username");
username.addChild(Node.TEXT, HttpConstant.REQ_HEADER_USERNAME);
usernametoken.addChild(Node.ELEMENT,username);
// password
Element password = new Element().createElement(security.getNamespace(), "Password");
password.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
password.addChild(Node.TEXT, HttpConstant.REQ_HEADER_PASSWORD);
usernametoken.addChild(Node.ELEMENT,password);
headers[0].addChild(Node.ELEMENT, usernametoken);
return headers[0];
}

Android :Problem with parameter passing(webservices)

I am new to web services and I got a problem with the response in the logcat. I am passing all my parameters to the server but the response is some what unreliable and I goggled a lot to find out the solution, but I cant.I am using Ksoap, WSDL in my webservices
The logcat message is this
06-17 14:20:31.168: VERBOSE/TAG(302): `RegisterUserResponse{RegisterUserResult=-1; }`
someone plz help me to solve this
private static final String SOAP_ACTION = "http://tempuri.org/RegisterUser";
private static final String METHOD_NAME = "RegisterUser";
private static final String NAMESPACE = "http://tempuri.org";
private static final String URL = "http://........";
private static final String TAG = "HELLO";
Thread t;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button signin = (Button) findViewById(R.id.regsubmitbtn);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(0);
t = new Thread() {
public void run() {
register();
}
};
t.start();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: {
dialog = new ProgressDialog(this);
dialog.setMessage("Please wait while connecting...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
Button regmalebtn;
public void register() {
Log.v(TAG, "Trying to Login");
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
// String response1 = request.getProperty(0).toString() ;
request.addProperty("fname", "raghav");
request.addProperty("lname", "raju");
request.addProperty("dateofbirth", "18-01-1985");
request.addProperty("email", "raghuraju90#yahoo.com");
request.addProperty("password", "1234");
//request.addProperty("password", repassword);
request.addProperty("mobno", "8553456260");
request.addProperty("latitude", "76");
request.addProperty("longitude", "82");
request.addProperty("device_id", "123456");
request.addProperty("gender", "male");
// request.addProperty("latitude',latitude);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call(SOAP_ACTION, soapEnvelope);
androidHttpTransport
.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
SoapObject resultsRequestSOAP = (SoapObject) soapEnvelope.bodyIn;
// SoapObject result = (SoapObject) soapEnvelope.getResponse();
Log.v("TAG", String.valueOf(resultsRequestSOAP));
String resultData;
resultData = request.getProperty(0).toString();
}
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
That error is being generated by the server. You'll need to speak with the developer / owner of the server and get them to check their logs to determine why your transaction is failing.

Categories

Resources