ANDROID: KSOAP2 HttpsTransportSE slow response or timeout - java

I'm using HttpsTransportSE for calling webservices. Repeatedly calling web service which needs for reply 1-2s. Then there is a call which requires 30-45s or return timeout(set on 45s). This problem occurs only on 3G signal on WIFI works perfectly.
public SoapObject CallWS(Object object, ArrayList<Tuples> params,
String SOAP_ACTION, String METHOD_NAME, String NAMESPACE, String serviceURL) {
SoapObject response = null;
//try {
// Generate soap object with WS-namespace and WS-method name
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Parameters for WS method
for (int i = 0; i < params.size(); i++) {
request.addProperty(params.get(i).getLeft().toString(), params
.get(i).getRight().toString());
}
// Create soap envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader(NAMESPACE,"trak8","g3s0");
// Add mapping for complex parameter
envelope.addMapping(NAMESPACE, "Object", new Object().getClass());
TrustManagerManipulator.allowAllSSL();
Log.i("NAMESPACE",NAMESPACE);
Log.i("METHOD_NAME",METHOD_NAME);
Log.i("URL2",serviceURL);
//HttpTransportSE aht = new HttpTransportSE(serviceURL, 10000);
String[] serviceURLSplit = serviceURL.split("//");
String[] serviceURLSplitMethod = serviceURLSplit[1].split("/");
HttpsTransportSE aht = new HttpsTransportSE(serviceURLSplitMethod[0], 443,"/"+serviceURLSplitMethod[1], 45000);
List<HeaderProperty> headerList = new ArrayList<HeaderProperty>();
headerList.add(new HeaderProperty("Connection", "keep-alive"));
try {
Log.i("StatusCall", "calling ws"+METHOD_NAME); // For debbug only
aht.call(SOAP_ACTION, envelope,headerList);
response = (SoapObject) envelope.getResponse();
Log.i("StatusCall", "response successfully recived"); // For debbug
// only
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
`

Related

How to add "content-type" header in soap webservice

I've seen several different examples and I can't get any to work. My goal is to add a content type of JSON to my request. Without the header, my request doesn't error:
public void calculate() {
String SOAP_ACTION = "http://----/--";
String METHOD_NAME = "----";
String NAMESPACE = "http://-----/";
String URL = "http://----/---/----.asmx";
try {
// Creating a new empty SOAP message object
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("username", "***");
Request.addProperty("password", "****");
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
resultString = (SoapPrimitive) soapEnvelope.getResponse();
Log.i(TAG, "Result Celsius: " + resultString);
} catch (Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
}
Try this,
// Create a of HeaderProperty
List<HeaderProperty> headerList = new ArrayList<HeaderProperty>();
// Add Content-Type to the list
headerList.add(new HeaderProperty("Content-Type", "application/json; charset=UTF-8"));
// Pass this list as 3rd argument to call method
transport.call(SOAP_ACTION, soapEnvelope, headerList);

how to get each element of this array in java using android stuio

I get the string of array on responseJSON like this
Result: responseJSON = ["Product1","Product2","Product1","Product2"]
try {
// Invole web service
androidHttpTransport.call(SOAP_ACTION+methName, envelope);
// Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// Assign it to static variable
responseJSON = response.toString();
} catch (Exception e) {
e.printStackTrace();
}
how can to get each element of the array so that I can use it to display on my ListView?
Thanks
public void invokeJSONWS(String country, String methName) {
// Create request
SoapObject request = new SoapObject(NAMESPACE, methName);
/*
// Property which holds input parameters
PropertyInfo paramPI = new PropertyInfo();
// Set Name
paramPI.setName("country");
// Set Value
paramPI.setValue(country);
// Set dataType
paramPI.setType(String.class);
// Add the property to request object
request.addProperty(paramPI);
*/
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invole web service
androidHttpTransport.call(SOAP_ACTION+methName, envelope);
// Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// Assign it to static variable
responseJSON = response.toString();
JSONArray responseArr = new JSONArray(responseJSON);
for(int i=0;i < responseArr.length();i++)
{
String temp=responseArr.getString(i);
myProduct.add(new Product(responseJSON,2,R.drawable.user_awake,responseJSON));
}
} catch (Exception e) {
e.printStackTrace();
}
}
this is the method that i used it it correct that i also include the adding an item in the list view??
please help
thanks
pass this string to JSONAarry constructor like this
ArrayList<String> mParsedList = new ArrayList<String>();
JSONAarry responseArr=new JSONArray(responseJSON);
for(int i=0;i<responseArr.length;i++)
{
String temp=responseArr.getString(i);// get one by one element
myProduct.add(new Product(temp,2,R.drawable.user_awake,responseJSON));
}

(JAVA) SOAP WebService error object reference not set to an instance of an object

i am trying to set up connection to SOAP WebService from Android app but every time i get wried error in my result :
object reference not set to an instance of an object java
It seems to be error from server --> SOAP Webservice call from Java gives "Object reference not set to an instance of an object"
But when i try it throught web browser with POST request it works fine :)
This service http://ws.cdyne.com/ip2geo/ip2geo.asmx?op=ResolveIP
private static String NAMESPACE = "http://ws.cdyne.com/";
private static String URL = "http://ws.cdyne.com/ip2geo/ip2geo.asmx";
private static String SOAP_ACTION = "http://ws.cdyne.com/";
public static String invokeHelloWorldWS(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo sayHelloPI = new PropertyInfo();
// Set name
sayHelloPI.setName("ipAddress");
// Set Value
sayHelloPI.setValue("88.212.35.129");
// Set dataType
sayHelloPI.setType(String.class);
// Add the property to request object
request.addProperty(sayHelloPI);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try{
// Invoke web service
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope); //webMethName = "ResolveIP"
// Get the response
Log.d("a", androidHttpTransport.responseDump);
//SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// Assign it to resTxt variable static variable
//resTxt = response.toString();
}catch(Exception e){
//Print error
e.printStackTrace();
}
}
I spend lot of time on google but i cant figure right answer why this happend
// EDIT
Finally i get it right ... idk why but when i send second parameter like this (i reuse old property) :
sayHelloPI.setName("licenseKey");
sayHelloPI.setValue("some_key");
sayHelloPI.setType(String.class);
request.addProperty(sayHelloPI);
it wasnt working. But when i make new Property object it works:
PropertyInfo sayHelloPI1 = new PropertyInfo();
sayHelloPI1.setName("licenseKey");
sayHelloPI1.setValue("ds");
sayHelloPI1.setType(String.class);
request.addProperty(sayHelloPI1);
Maybe it help someone next time
This is some code that I have used myself - Hope it will help you:
// Initialize soap request + add parameters
SoapObject request = new SoapObject(getString(R.string.Namespace),
getString(R.string.Method_Name_GetStudentsByTeam));
Log.d("GetStudentsByTeamTask", "SOAP request");
// Use this to add parameters
request.addProperty("teamId", params[0]);
Log.d("GetStudentsByTeamTask", "id: " + params[0]);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
Log.d("GetStudentsByTeamTask",
"Declared the version of the SOAP request");
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
Log.d("GetStudentsByTeamTask", "Setting som variables");
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(
getString(R.string.URL));
Log.d("GetStudentsByTeamTask", "Instance the HttpTransportSE");
// this is the actual part that will call the webservice
androidHttpTransport.call(
getString(R.string.Soap_Action_GetStudentsByTeam),
envelope);
Log.d("GetStudentsByTeamTask", "Called the Webservice");
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.getResponse();
Log.d("GetStudentsByTeamTask", "Got the Soapresult");
if (result != null) {
// Do something with result
// success = true;
Log.d("GetStudentsByTeamTask", "set sucess boolean to true");
for (int i = 0; i < result.getPropertyCount(); i++) {
PropertyInfo pi = new PropertyInfo();
result.getPropertyInfo(i, pi);
Log.d("GetStudentsByTeamTask",
pi.name + " : " + result.getProperty(i));
SoapObject obj = (SoapObject) result.getProperty(i);
Student student = new Student();
student.address = obj.getProperty("Address").toString();
student.city = obj.getProperty("City").toString();
student.created = DateTime.parse(obj.getProperty(
"Created").toString());
student.dateOfBirth = DateTime.parse(obj.getProperty(
"DateOfBirth").toString());
student.email = obj.getProperty("Email").toString();
student.firstname = obj.getProperty("FirstName")
.toString();
student.id = Integer.parseInt(obj.getProperty("ID")
.toString());
student.imageId = Integer.parseInt(obj.getProperty(
"ImageID").toString());
// SoapObject lastNameObject = (SoapObject) obj
// .getProperty("LastName");
//
student.lastName = obj.getProperty("LastName")
.toString();
student.phone = obj.getProperty("Mobile").toString();
student.zipcode = obj.getProperty("PostalCode")
.toString();
student.schoolId = Integer.parseInt(obj
.getPropertyAsString("SchoolId"));
student.teamId = Integer.parseInt(obj
.getPropertyAsString("TeamId"));
student.testStarted = Integer.parseInt(obj
.getPropertyAsString("TestsStarted"));
student.timeStamp = DateTime.parse(obj
.getPropertyAsString("TimeStamp"));
student.image = getImage(Integer.parseInt(obj
.getProperty("ImageID").toString()));
if (student.image == null)
student.image = BitmapFactory
.decodeResource(getResources(),
R.drawable.default_usericon);
MyApp.getController().addStudent(student);
}
} else {
// If fails
// success = false;
Log.d("GetStudentsByTeamTask", "set login boolean to false");
}
} catch (Exception e) {
Log.d("GetStudentsByTeamTask", "FAILED! " + e.getMessage());
e.printStackTrace();
}

Unable to login via KSOAP Android to Web Service

This is my primitive web-service:
#Override
public boolean LogOn(String UserName, String Password) {
String username = "";
String password = "";
if (UserName != null) {
username = UserName;
}
if (Password != null) {
password = Password;
}
System.out.println("username is"+username);
System.out.println("password is"+password);
//test parameters
if (username.equals("admin") && password.equals("admin")) {
return true;
} else {
return false;
}
}
This client on Android:
private static final String METHOD_NAME = "LogOn";
private static final String NAMESPACE = "http://calculator.me.org/";
private static final String URL = "http://10.0.2.2:8080/logon/WebServiceImplService?wsdl";
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Add the input variables for the method
request.addProperty("username", "admin");
request.addProperty("password","admin");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
System.setProperty("http.keepAlive", "false");
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug=true;
androidHttpTransport.call(getSoapAction(METHOD_NAME), envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
//get response from web server
String d =result.getProperty("return").toString();
// Logging the raw request and response (for debugging purposes)
Log.d(TAG, "HTTP REQUEST:\n" + androidHttpTransport.requestDump);
Log.d(TAG, "HTTP RESPONSE:\n" + androidHttpTransport.responseDump);
Log.i(TAG,"response from service:"+d);
if(d.equals("true"))
{
//The result will be here, use it wisely :)
return 1;
}
else
return 0;
} catch (Exception e) {
Log.e(TAG,"doInBackground failed"+e);
e.printStackTrace();
return 0;
}
}
When i'm manual testing web-service, log web-service:
INFO: username isadmin
INFO: password isadmin
When i'm trying login from android client, i'm get next log:
INFO: username is
INFO: password is
If i'm delete nullpointer check, on web-service i'm get NullPointerException.
Logs from Android client:
11-12 02:29:55.081: D/SmsSender:LogOnAsync(1878): HTTP REQUEST:
11-12 02:29:55.081: D/SmsSender:LogOnAsync(1878): <v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /><v:Body><n0:LogOn id="o0" c:root="1" xmlns:n0="http://calculator.me.org/"><username i:type="d:string">admin</username><password i:type="d:string">admin</password></n0:LogOn></v:Body></v:Envelope>
11-12 02:29:55.081: D/SmsSender:LogOnAsync(1878): HTTP RESPONSE:
11-12 02:29:55.081: D/SmsSender:LogOnAsync(1878): <?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:LogOnResponse xmlns:ns2="http://calculator.me.org/"><return>false</return></ns2:LogOnResponse></S:Body></S:Envelope>
11-12 02:29:55.081: I/SmsSender:LogOnAsync(1878): response from service:false
What's wrong?
I have a similar problem. I'm decided to read:
Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi1 = new PropertyInfo();
pi1.setName("arg0");
pi1.setValue("admin");
pi1.setType(String.class);
request.addProperty(pi1);
PropertyInfo pi2 = new PropertyInfo();
pi2.setName("arg1");
pi2.setValue("admin");
pi2.setType(String.class);
request.addProperty(pi2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
System.setProperty("http.keepAlive", "false");
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug=true;
androidHttpTransport.call(getSoapAction(METHOD_NAME), envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
//get response from web server
String d =result.getProperty("return").toString();
// Logging the raw request and response (for debugging purposes)
Log.d(TAG, "HTTP REQUEST:\n" + androidHttpTransport.requestDump);
Log.d(TAG, "HTTP RESPONSE:\n" + androidHttpTransport.responseDump);
Log.i(TAG,"response from service:"+d);
if(d.equals("true"))
{
//The result will be here, use it wisely :)
return 1;
}
else
return 0;
} catch (Exception e) {
Log.e(TAG,"doInBackground failed"+e);
e.printStackTrace();
return 0;
}
}
This will help only if you brought the whole method LogOn

Android ksoap web service issue getting pullParserExcepstion

I am consuming a .net web service using ksoap2 but getting the following Exception:
org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null#1:1 in java.io.InputStreamReader#412caa08)`
My request dump is the same as I needed but I'm not getting response dump and it has come as null. I am trying, but getting the same error.Please some one help me. My code is given below-
public class Login extends Activity {
private final String NAMESPACE = "http://xyz.public/imageupload/1.0/";
private final String URL = "http://public.service.xyz.com/ImageUpload.svc";
private final String SOAP_ACTION = "http://xyz.public/imageupload/1.0/Services/Authentication";
private final String METHOD_NAME = "Authentication";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
SoapSerializationEnvelope envelope = null;
SoapObject request = null;
HttpTransportSE httpTransportSE = null;
try {
request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userId", "admin");
request.addProperty("password", "password");
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.ENC;
/**
* below code for custom header
*/
Element actionElement = new Element().createElement(null,
"d:Action");
actionElement.setAttribute("", "s:mustUnderstand", "1");
actionElement.addChild(Node.TEXT, SOAP_ACTION);
Element toElement = new Element().createElement(null, "d:To");
toElement.setAttribute("", "s:mustUnderstand", "1");
toElement.addChild(Node.TEXT, URL);
Element[] header = { actionElement,toElement };
envelope.headerOut = header;
envelope.env = "http://schemas.xmlsoap.org/soap/envelope/";
/**
* Custom header part end
*/
envelope.setOutputSoapObject(request);
httpTransportSE = new HttpTransportSE(URL);
httpTransportSE.debug = true;
httpTransportSE.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.getResponse();
// To get the data.
String textResult = result.toString();
Log.i("textResult", textResult);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e("Exception:", e.toString());
}
finally {
Log.i(getClass().getSimpleName(), "requestDump : "+ httpTransportSE.requestDump);
Log.i(getClass().getSimpleName(), "responseDump : "+ httpTransportSE.responseDump);
}
}
}

Categories

Resources