SocketTimeoutException: connect timed out Android ksoap - android

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?

Related

org.xmlpull.v1.XmlPullParserException: expected: START_TAG in api calling

I am new bee in android. I am trying parse data using soap api. Following is my snippet code. When I run the project I am getting following error can any one help me with this? Following is my snippet code. I am not able to find the issue what exactly I am facing. sorry for bad english.
Error
W/System.err: org.xmlpull.v1.XmlPullParserException: expected:
START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope
(position:START_TAG #4:44 in java.io.InputStreamReader#7f5b56a)
Code
public class GetReport extends Activity {
private static final String NAMESPACE = "https://www.myweb.co.ke/Wt/"; // com.service.ServiceImpl
private static final String URL = "https://www.myweb.co.ke/Wt/webtask.asmx";
private static final String METHOD_NAME = "GetProductListing";
private static final String SOAP_ACTION = NAMESPACE+METHOD_NAME;
private String webResponse = "";
private Handler handler = new Handler();
private Thread thread;
private TextView textView1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(1);
setContentView(R.layout.test_demo);
textView1 = (TextView) findViewById(R.id.ttte);
startWebAccess("title");
}
public void startWebAccess(String a) {
final String aa = a;
thread = new Thread() {
public void run() {
try {
Log.d("Req value0R", "Starting...");// log.d is used for
// debug
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
/* request.addProperty("ClientCode", "64396");
request.addProperty("key", "Om$#!##M^#R");*/
request.addProperty("User Name", "1234");
request.addProperty("Password", "4321");
Log.d("Req value1", request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject objectResult = (SoapObject) envelope.bodyIn;
webResponse = objectResult.toString();
System.out.println("response: " + webResponse);
} catch (SoapFault sp) {
sp.getMessage();
System.out.println("error = " + sp.getMessage());
} catch (Exception e) {
System.out.println("problem8");
e.printStackTrace();
webResponse = "Connection/Internet problem";
}
handler.post(createUI);
}
};
thread.start();
}
final Runnable createUI = new Runnable() {
public void run() {
if (webResponse != null) {
textView1.setText(webResponse);
} else {
webResponse = "No data provided presently";
textView1.setText(webResponse);
}
}
};
}

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 :)

Android Studio Webservice call "HTTP request failed, HTTP status: 401" Unauthorized

i try to connect my Android application to a Webservice.
I wrote a new class and defined some Variables:
I´ve got the Async Class to use the Network
class GetValueTask extends AsyncTask<ApiConnector,Long,String> {
#Override
protected String doInBackground(ApiConnector... params) {
//wird im Background Thread ausgeführt
return params[0].getValue();
}
#Override
protected void onPostExecute(String s) {
//wird im Mainthread ausgeführt
MainActivity.this.setText(s);
}
}
And I have a Class where i want to call the Webservice
public class ApiConnector
{
private static final String SOAP_ACTION ="urn:microsoft-dynamics-schemas/codeunit/AddService:Add";
private static final String METHOD_NAME ="Add";
private static final String NAMESPACE ="urn:microsoft-dynamics-schemas/codeunit/AddService";
private static final String URL ="http://192.168.0.154:9047/DynamicsNAV80/WS/CRONUS%20AG/Codeunit/AddService";
private static final String USERNAME="B.Denger";
private static final String PASSWORD ="TestPW123!";
public String getValue() {
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
request.addProperty("no","10");
PropertyInfo unamePI = new PropertyInfo();
PropertyInfo passPI = new PropertyInfo();
// Set Username
unamePI.setName("username");
// Set Value
unamePI.setValue(USERNAME);
// Set dataType
unamePI.setType(String.class);
// Add the property to request object
request.addProperty(unamePI);
//Set Password
passPI.setName("password");
//Set dataType
passPI.setValue(PASSWORD);
//Set dataType
passPI.setType(String.class);
//Add the property to request object
request.addProperty(passPI);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE aht= new HttpTransportSE(URL);
try {
aht.call(SOAP_ACTION, soapEnvelope);
SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
return resultString.toString();
}catch(Exception e ) {
e.printStackTrace();
return "Fail at Call";
}
}
}
I have set the using-permission in the Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
in my MainActivity do i execute the AsynkTask with a Button
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetValueTask getValueTask = new GetValueTask();
getValueTask.execute(new ApiConnector());
}
});
after execution i get following Logcat entry:
W/System.err﹕ org.ksoap2.transport.HttpResponseException: HTTP request failed, HTTP status: 401
i googled a whole Day for it, but i did not solved the problem yet.
is there anybody who could help me, or could give me a hint where i have to search?
I found the solution here:
Android Consuming Dynamics NAV SOAP Web Service
but it didnt Work with the jcif 1.3.17 jar
at https://jcifs.samba.org/src/ can you download the latest version.
In my case I fixed same problem by adding this code:
List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
Complete task:
private class fnAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params)
{
//for linear parameter
SoapObject loRequest = new SoapObject(sNAMESPACE, sMETHOD_NAME);
// adding method property here serially
// loRequest.addProperty("CountryName", "france");
SoapSerializationEnvelope loEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
loEnvelope.implicitTypes = true;
loEnvelope.setOutputSoapObject(loRequest);
loEnvelope.dotNet = true;
HttpTransportSE loHttpTransport = new HttpTransportSE(_sURL);
loHttpTransport.debug = true;
try
{
List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
}
catch (HttpResponseException e)
{
// TODO Auto-generated catch block
Log.e("HTTPLOG", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IOLOG", e.getMessage());
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
Log.e("XMLLOG", e.getMessage());
e.printStackTrace();
} //send request
Object result = null;
try {
result = (Object )loEnvelope.getResponse();
//See output in the console
Log.i("RESPONSE",String.valueOf(result));
} catch (SoapFault e) {
// TODO Auto-generated catch block
Log.e("SOAPLOG", e.getMessage());
e.printStackTrace();
}
return null;
}
}
Full example
http://www.nascenia.com/consuming-soap-web-services-from-android/

How to send request post method in svc(soap) service in 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();
}

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

Categories

Resources