Getting Exception While Invoking Web Service From Android - java

I am a beginner in this, i am facing an issue while invoking asp.net web service method (SignUp) from android. It works fine when i try it from browser but when i do it from the android it gives me some exception like
"
SoapFault - faultcode: 'soap:Client' faultstring: 'System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: SignUp.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)' faultactor: 'null' detail: org.kxml2.kdom."
This is my Java Signup class
String SOAP_ACTION1 = "http://tempuri.org/SignUp";
String METHOD_NAME1 = "SignUp";
btn = (Button)findViewById(R.id.btn_signup);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new WebService().execute(METHOD_NAME1,SOAP_ACTION1,txt_name.getText().toString(), txt_email.getText().toString(),txt_password.getText().toString(),
txt_address.getText().toString(),
txt_dob.getText().toString(),
txt_account.getText().toString(),
txt_cnic.getText().toString(),txt_pobox.getText().toString(),
txt_city.getText().toString(),txt_status.getText().toString());
This is My Java WebService Class
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://192.168.0.102/MyWebService/WebService1.asmx?WSDL";
protected String doInBackground(String... params) {
String s="";
String whichmethodcall = params[0];
switch(whichmethodcall){
case "SignUp":
s = signup(params);
break;
case "SignIn":
s = signin(params);
break;
}
return s;
}
public String signup(String[] arr){
String s = "";
SoapObject request = new SoapObject(NAMESPACE, arr[1]);
//Use this to add parameters
request.addProperty("cname",arr[2]);
request.addProperty("cemail",arr[3]);
request.addProperty("cpwd",arr[4]);
request.addProperty("caddress",arr[5]);
request.addProperty("cdob",arr[6]);
request.addProperty("caccount",arr[7]);
request.addProperty("cCnic",arr[8]);
request.addProperty("cpobox",arr[9]);
request.addProperty("cCity",arr[10]);
request.addProperty("cstatus",arr[11]);
//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(arr[0], envelope);
// Get the SoapResult from the envelope body.
// SoapObject result = (SoapObject)envelope.bodyIn;
// SoapObject result = (SoapObject) envelope.getResponse();
if (envelope.bodyIn instanceof SoapFault) {
final SoapFault result = (SoapFault) envelope.bodyIn;
if (result != null) {
//Get the first property and change the label text
s = result.toString();
} else
s = "No response";
}
} catch (Exception e) {
e.printStackTrace();
s=e.getMessage().toString();
}
return s;
}
And This is My asp.net WebService method
public string SignUp(string cname, string caddress, string cdob, long caccount, long cCnic, int cpobox, string cCity, string cstatus,string cemail, string cpass)
{
bool check = ConnectDB(); // Opens the Connection to Insert The new User
string msg = "";
//DateTime dob = DateTime.ParseExact(cdob, "dd/mm/yyyy", null);
string query = "INSERT INTO Customers values('" + cname + "','" + caddress + "','" + cdob + "','" + caccount + "','" + cCnic + "','" + cpobox + "','" + cCity + "','" + cstatus + "','"+ cemail + "','"+ cpass + "')";
SqlCommand comm = new SqlCommand(query, con);
try{
if (check == true){
if (comm.ExecuteNonQuery() > 0)
msg = "you've signed up !";
else
msg = "sign up error";
}
else
msg = "Database not Connected";
}catch (SqlException ex){
msg = ex.Message.ToString();
con.Close();
}finally{
con.Close();
}
return msg;
}

Can you try this
instead of SoapObject request = new SoapObject(NAMESPACE, arr[1]);
use
SoapObject request = new SoapObject(NAMESPACE, arr[0]);
In the soap object you should pass just method name, without http://...

Related

Executing a java class in Eclipse

I have a java project in Eclipse which was written by some other developer. I am very new to Java and have made some modifications in the source code. Now i want to test the code by executing it in eclipse. How can I create a main class and execute the modified code.
Following is the class file which I want to run
public class Bio_Verify extends AbstractOutboundServiceProvider
{
public static String EndPointURL = null;
public static String ApiKey = null;
public static String Version = null;
public static String EntityId = null;
public static String requestId = null;
public static String EncryptionKey = null;
public static String SignatureKey = null;
public static String SignAlgorithm = null;
public String requestData = null;
public String requestXML = null;
public String response = null;;
public String errorMsg;
public void preprocess(IUsbMessage inputMsg)
{
LogManager.logDebug("Bio_Verify: preprocess():: inside preprocess");
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: START");
}
public IUsbMessage executeOutboundRequest(String inputMsg)
{
int i = 0;
int j = 0;
String resolution = null;
String key = null;
String criteria = null;
String position = null;
String format = null;
String data = null;
String intent = null;
String resBodyXML = null;
String outputXMLMsg = null;
String[] responseMsg = new String[2];
IUsbMessage outMsg = null;
Verify verify = new Verify();
Fingerprint fingerprint = new Fingerprint();
requestData = "CN01473|cif|UNKNOWN_FINGER|508|BMP|Qk12WeoAAAA=|verify";
//Forming requestId for Bio
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
requestId = dateFormat.format(date);
EndPointURL = OutboundConstants.Bio_Endpoint;
ApiKey = OutboundConstants.ApiKey;
Version = OutboundConstants.Version;
EntityId = OutboundConstants.EntityId;
EncryptionKey = OutboundConstants.EncryptionKey;
SignAlgorithm = OutboundConstants.SignAlgorithm;
SignatureKey = OutboundConstants.SignatureKey;
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Bio_Endpoint URL is " + EndPointURL);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Api Key is " + ApiKey);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Version is " + Version);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: EntityId is " + EntityId);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: EncryptionKey is " + EncryptionKey);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: SignatureKey is " + SignatureKey);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: SignAlgorithm is " + SignAlgorithm);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Request Id is " + requestId);
//Extraction data from the request XML
for(i=0;i<7;i++){
int x = requestData.indexOf("|");
int y = requestData.length();
if(i==0){
key = requestData.substring(0, x);
LogManager.logDebug("Key: "+key);
requestData = requestData.substring(x+1,y);
}
if(i==1){
criteria = requestData.substring(0, x);
LogManager.logDebug("Criteria: "+criteria);
requestData = requestData.substring(x+1,y);
}
if(i==2){
position = requestData.substring(0, x);
LogManager.logDebug("Position: "+position);
requestData = requestData.substring(x+1,y);
}
if(i==3){
format = requestData.substring(0, x);
LogManager.logDebug("Format: "+format);
requestData = requestData.substring(x+1,y);
}
if(i==4){
resolution = requestData.substring(0, x);
LogManager.logDebug("Resolution: "+resolution);
requestData = requestData.substring(x+1,y);
}
if(i==5){
data = requestData.substring(0, x);
requestData = requestData.substring(x+1,y);
}
if(i==6){
intent = requestData;
LogManager.logDebug("Intent: "+intent);
}
}
FingerprintImage fingerprintimage = new FingerprintImage(format,resolution,data);
fingerprint.image = fingerprintimage;
fingerprint.position = position;
responseMsg = verify.verify(key, criteria, fingerprint, intent);
this.errorMsg = responseMsg[0];
this.response = responseMsg[1];
LogManager.logDebug("Back in bio verify - array element1"+this.errorMsg);
LogManager.logDebug("Back in bio verify - array element2"+this.response);
outMsg = UsbMessageFactory.createUbusMessage();
outMsg.setMsgType("XML");
outMsg.setMsgSubType("FIXML");
LogManager.logDebug("Bio: executeOutboundRequest():: errorMsg=" + errorMsg);
if (errorMsg.toString().trim().length() > 0)
{
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Inside FAILURE");
outMsg.setBackEndTranStatus("FAILURE");
outMsg.setErrMsgFlg(1);
outMsg.setPayload(new Object[] { new CIFatalException(errorMsg.toString()) });
}
else
{
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: Inside SUCCESS");
outMsg.setBackEndTranStatus("SUCCESS");
outMsg.setErrMsgFlg(0);
resBodyXML = this.response.toString();
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: outputXMLMsg XML:" + outputXMLMsg);
outMsg.setPayload(new Object[] { outputXMLMsg });
}
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: outMsg:" + outMsg);
LogManager.logDebug("Bio_Verify: executeOutboundRequest():: END");
return outMsg;
}
Can you follow the steps , this will help to you
There are 6 steps are below added ( I think you will get idea how to archive your problem )
1.Right click inside package and you can see CLASS then it will pop up this attached window
2. Insight Main method you can crate some object like I have created and pass parameter what you want (You just understand what method you have to call )
You have to write main function into Bio_Verify class.
main function is boot function.
So if you write main function, you can execute this class.
ex)
public class BioVerify extends AbstractOutboundServiceProvider {
public static void main(String[] args) {
// TODO: Write a code....
}
}
write the main function below to the code and create object for BIO_verify class and it's function

Getting error when insert birth date into a database

I'm trying to insert contacts details to a MySQL database,
Here is my code :
public void SyncContact(){
ContentResolver cr = getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
JSONArray ja = new JSONArray();
HashMap<String,String> hashmap_contactList = new HashMap<String, String>();
String id="";
String name="";
String mobileNo="";
String emailContact="";
String orgName="";
String title="";
String note="";
String street="";
String dob="";
int i = 0;
while (phones.moveToNext()) {
id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
mobileNo = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
if(emailCur.getCount()>0) {
while (emailCur.moveToNext()) {
emailContact = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
}else{
emailContact="";
}
emailCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, orgWhereParams, null);
if(orgCur.getCount()>0) {
if (orgCur.moveToFirst()) {
orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
}else{
orgName="";
title="";
}
orgCur.close();
String[] noteWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, noteWhereParams, null);
if(noteCur.getCount()>0) {
if (noteCur.moveToFirst()) {
note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
}
}else{
note="";
}
noteCur.close();
String[] addrWhereParams = new String[]{id,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, addrWhereParams, null);
if(addrCur.getCount()>0){
while(addrCur.moveToNext()) {
street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
}
}else {
street="";
}
addrCur.close();
String[] selectionArgs = new String[] {id,ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
Cursor dobCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, selectionArgs, null);
if(dobCur.getCount()>0) {
if (dobCur.moveToFirst()) {
dob = dobCur.getString(dobCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.DATA));
}
}else {
dob="";
}
dobCur.close();
if(!hashmap_contactList.containsKey(name)){
hashmap_contactList.put(name, " ");
System.out.println("!! Contact ID is : " + id);
System.out.println("!! Contact Name is : " + name);
System.out.println("!! Contact Number is : " + mobileNo);
System.out.println("!!prepare Email " + emailContact );
System.out.println("!!prepare Comapny name:" + orgName);
System.out.println("!!prepare Designation :" + title);
System.out.println("!!prepare Note :" + note);
System.out.println("!!prepare Street:" + street);
System.out.println("!!hello dob :" + dob);
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("contact_uniqueid",id);
jsonObject.put("contact_name",name);
jsonObject.put("contact_number",mobileNo);
jsonObject.put("email",emailContact);
jsonObject.put("oraganization",orgName);
jsonObject.put("job_title",title);
jsonObject.put("address",street);
jsonObject.put("note",note);
jsonObject.put("dob",dob);
ja.put(jsonObject);
mainjson.put("data",ja);
}catch (Exception e){
e.printStackTrace();
}
i++;
}
}
phones.close();
System.out.println("!!json " + mainjson);
try {
Log.d("!!!main_json", mainjson.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ContactSync contactSync = new ContactSync();
contactSync.execute();
}
public class ContactSync extends AsyncTask<String,Void,String>{
String JsonString;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpPost post = new HttpPost(str_url);
try{
StringEntity entity = new StringEntity(mainjson.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
System.out.println("!!Response : " + response);
JSONObject jsonObject = new JSONObject(response);
System.out.println("!!Response " + jsonObject);
System.out.println("!! " + jsonObject.getString("data"));
JSONObject success_status = jsonObject.getJSONObject("data");
System.out.println("!!Succes MSg :" + success_status.getString("success"));
if(success_status.getString("success").toString().equalsIgnoreCase("true"))
{
System.out.println("Response after data inserted....."+success_status.getString("success").toString());
CommonFunction.saveSharedPreference(CommonFunction.contactsync_flag, "1", SplashActivity.this);
}
}catch (Exception e){
e.printStackTrace();
System.out.println("!! : "+e.getMessage());
System.out.println("!!!!!!manishhhhhhh......" );
}
return null;
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
And the API Code is :
public function temp(){
$_POST = json_decode(file_get_contents('php://input'), true);
$this->load->library('form_validation');
$boolean = TRUE;
$data = array();
$contact_data = $_POST['data'];
$i=0;
foreach($contact_data AS $row){
$fields['contact_uniqueid']=$row['contact_uniqueid'];
$fields['contact_name']=$row['contact_name'];
$fields['contact_number']=$row['contact_number'];
$fields['email']=$row['email'];
$fields['oraganization']=$row['oraganization'];
$fields['job_title']=$row['job_title'];
$fields['address']=$row['address'];
$fields['note']=$row['note'];
$fields['dob']=$row['dob'];
$data[$i] = $fields;
$i++;
}
$this->express_model->set_table('contact_list');
$data_obj = $this->express_model->saveBatch($data);
if ($boolean == TRUE)
{
$final_data['data']['success'] = 'true';
$final_data['data']['message'] = 'Data inserted successfully';
print_r(json_encode($final_data));
}
exit;
}
All contacts details are inserted into the database and I have to get "true" in the JSON response but I'm getting this error:
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
and I use PHP API written in codeigniter.
check the data type into your database schema and try to insert the appropriate value..
Mostly it happen when we use DateTime data type for fields

java.io.IOException: HTTP request failed, HTTP status: 500 (ksoap2)

I'm using KSOAP2, when sending request to the server and got java.io.IOException: HTTP request failed, HTTP status: 500 in the line httpTransport.call(SOAP_ACTION, envelope) , but server works, I have checked it using SoapUI. What can be the problem?
public class SOAPClient
{
private static final int TIMEOUT_SOCKET = 180000;
public static SoapObject get(Context context, String methodName, ArrayList<Pair<String, ?>> args) throws Exception
{
final String URL = PrefHelper.getSOAPUrl(context);
final String NAMESPACE = PrefHelper.getSOAPNamespace(context);
final String SOAP_ACTION = methodName; //NAMESPACE + "#" + "mapx" + ":" + methodName;
SoapObjectEve request = new SoapObjectEve(NAMESPACE, methodName);
if (args != null) {
for (Pair<String, ?> arg : args) {
if (arg.first != null) {
request.addProperty(arg.first, arg.second);
}
}
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
new MarshalBase64().register(envelope);
envelope.setOutputSoapObject(request);
envelope.implicitTypes = true;
HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT_SOCKET);
httpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
try
{
httpTransport.call(SOAP_ACTION, envelope);
AppLog.e(httpTransport.requestDump+"requestDump");
}
catch (ConnectTimeoutException e) {
AppLog.e(e.getMessage());
throw new Exception(context.getString(R.string.node_unavailable));
}
catch (SocketTimeoutException e) {
AppLog.e(e.getMessage());
throw new Exception(context.getString(R.string.timeout));
}
catch (Exception e) {
e.printStackTrace();
AppLog.e(e.getMessage());
AppLog.e(httpTransport.requestDump+"requestDump");
throw new Exception(context.getString(R.string.warning_error_get_data) + e.getMessage() == null ? "" : " " + e.getMessage());
}
AppLog.i(httpTransport.requestDump+"requestDump");
SoapObject soapObj = null;
try {
soapObj = (SoapObject) envelope.getResponse();
}
catch (Exception e) {
String response = ((SoapPrimitive) envelope.getResponse()).toString();
boolean res = Boolean.valueOf(response);
soapObj = new SoapObject();
soapObj.addProperty("response", res);
soapObj.addProperty("msg", "");
soapObj.addProperty("data", null);
}
AppLog.e(httpTransport.responseDump+"responseDump");
return soapObj;
}
}
Make sure your NAMESPACE, METHODNAME, WSDL and SOAP_ACTION are correct.
Try this code,
private static final String NAMESPACE = "http://www.kltro.com";
private static final String METHODNAME = "getUser";
private static final String WSDL = "http://ap.kashkan.org:55555/tro/ws/kltro";
private static final String SOAP_ACTION = NAMESPACE + "#kltro:" + METHODNAME ;
private static String TAG = "soap";
public static String callWebservice() {
String responseDump = "";
try {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
request.addProperty("login", login);
request.addProperty("pass", password);
request.addProperty("androidID", androidID);
request.addProperty("ver", version);
envelope.bodyOut = request;
HttpTransportSE transport = new HttpTransportSE(WSDL);
transport.debug = true;
try {
transport.call(SOAP_ACTION, envelope);
String requestDump = transport.requestDump;
responseDump = transport.responseDump;
Log.e(TAG, requestDump);
Log.e(TAG, responseDump);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return responseDump;
}
Also make sure you have internet permission in the manifest,
<uses-permission android:name="android.permission.INTERNET" />

What is proper practice for multithreading and httpclient in Java?

I'm creating a program that can do multiple logins. I will also give each login the ability to add an item to cart and purchase. The code is currently working for one account, and it's very basic. I had to trim out some private information, but the code should still be clear. Again, I'm just wondering what approach I should take for multiple logins? Does this code for the most part look optimal for speed? How do I approach a retry attempt if checkout returns 500? This code is currently setup for only a single login. Also, there weren't many articles I found to properly clean up the HttpClient. At least, I don't think the tutorials I found were very reputable.
Thanks again for taking the time to read this, I just want to learn other practices to improve my code and approach a proper multithreading technique.
Alittle more detail about my code, there is a token that is retrieved when you view the page, the token is stored and used throughout the program.
class example {
private static List<Header> headers = new ArrayList<Header>();
private static BasicCookieStore cookieStore = new BasicCookieStore();
private static CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).setDefaultCookieStore(cookieStore).build();
public static void main(String[] args) throws Exception {
String loginURL = "...";
String productUrl = "...";
String userid = "";
String password = "";
String formKey = "";
int size = 9;
Boolean debug = true;
JsonElement product;
headers.add(new BasicHeader("Host", "..."));
headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
headers.add(new BasicHeader("Accept-Language", "en-us"));
headers.add(new BasicHeader("Content-Encoding", "gzip, deflate"));
headers.add(new BasicHeader("Content-Type", "Application/x-www-form-urlencoded"));
headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_4_1 like Mac OS X) "
+ "AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4"));
headers.add(new BasicHeader("Connection", "keep-alive"));
Scanner in = new Scanner(System.in);
Gson gson = new Gson();
System.out.println("Select Profile\n1. ...\n2. Custom");
int select = in.nextInt();
switch(select) {
case 1:
userid = "...";
password = "...";
break;
// Custom Account Login
case 2:
System.out.println("Enter User_ID:");
userid = in.next();
System.out.println("Enter Password:");
password = in.next();
break;
}
int input = 0;
do {
input = in.nextInt();
switch(input) {
case 99:
debug = true;
break;
// View Menu.
case 0:
System.out.println("...");
break;
// Initiate Session
case 1:
// Retrieve formKey for login page.
formKey = getLogin(GetPageContent(loginURL));
session(formKey, userid, password, debug);
System.out.println("Press 0 to View Menu");
break;
case 2:
product = getProduct(GetPageContent(productUrl));
// Retrieve Product ID
Product productInfo = gson.fromJson(product.getAsJsonObject(), Product.class);
// Retrieve Color
Product[] color = gson.fromJson(product.getAsJsonObject().getAsJsonObject("attributes").getAsJsonObject("92").getAsJsonArray("options"), Product[].class);
// Prepare product request
String productKey = productInfo.getProductId();
String colorId = color[0].getId();
String postUrl = productInfo.getPostUrl();
// Execute addToCart
String result = addToCart(formKey, postUrl, productKey, colorId, size, debug);
break;
case 3:
String result2 = checkout(formKey);
break;
}
} while(input != 0);
}
public static void session(String formKey, String userid, String password, Boolean debug) {
HttpPost post = new HttpPost("...");
try {
// Package the data
StringEntity entity = new StringEntity("...");
post.setEntity(entity);
// Execute the data
HttpResponse response = httpClient.execute(post);
} catch (Exception e) {
e.printStackTrace();
} finally {
post.releaseConnection();
System.out.println("Login execution completed.");
}
}
public static String addToCart(String formKey, String postUrl, String productId, String colorId, int size, Boolean debug) {
String result = "";
HttpPost post = new HttpPost(postUrl);
try {
StringEntity entity = new StringEntity("...");
post.setEntity(entity);
// Execute the data
HttpResponse response = httpClient.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
// RETURN RESULT
result = EntityUtils.toString(response.getEntity());
if(debug) {
System.out.println("LOG: " + result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
post.releaseConnection();
System.out.println("Adding to cart execution completed.");
}
return result;
}
public static String GetPageContent(String url) throws Exception {
StringBuffer result = null;
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
request.releaseConnection();
}
return result.toString();
}
public static String getLogin(String html) {
String formKey = "";
Document doc = Jsoup.parse(html);
Element loginform = doc.getElementById("login-form");
Elements inputElements = loginform.getElementsByTag("input");
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("form_key"))
formKey = value;
}
return formKey;
}
public static JsonObject getProduct(String html)
throws UnsupportedEncodingException {
Document doc = Jsoup.parse(html);
System.out.println("Extracting form's data...");
Element form = doc.getElementById("product_addtocart_form");
Elements formElements = form.getElementsByTag("input");
String rawScript = form.getElementsByTag("script").html();
String script = "{" + rawScript.substring(rawScript.lastIndexOf("g({") + 3, rawScript.indexOf("}});")) + "}}";
// Create JSON object
JsonElement jelement = new JsonParser().parse(script.trim());
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject();
// Retrieve post link.
jobject.addProperty("postUrl", form.attr("action"));
return jobject;
}
public static String checkout(String formKey) {
HttpPost post = new HttpPost("...");
String result = "";
try {
StringEntity entity = new StringEntity("...");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200) {
result = EntityUtils.toString(response.getEntity());
System.out.println("Checkout Result: " + result);
} else if(status == 302) {
System.out.println("Checkout failed, Code: 302.");
} else if(status == 404) {
System.out.println("Checkout failed, Code: 404.");
} else if(status == 500) {
(insert retry step here)
System.out.println("Webserver is probably down. Code, 500.");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
post.releaseConnection();
}
return result;
}
}

JAVA web service receiving null parameters from Android Ksoap

I am trying to consume a JAVA web service from android.
Here is what I have tried so far:
private void CallWebServiceDummy() {
// TODO Auto-generated method stub
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
soapEnvelope.dotNet = false;
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
StringArraySerializer a = new StringArraySerializer();
a.add("hello"); a.add("world"); String n0 = NAMESPACE;
pi = new PropertyInfo(); pi.setName("a"); pi.setValue(a);
pi.setType(a.getClass()); pi.setNamespace(n0);
Request.addProperty(pi);
String b = "my name"; pi = new PropertyInfo(); pi.setName("b");
pi.setValue(b); Request.addProperty(pi);
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, soapEnvelope);
Log.d("test", "request: " + androidHttpTransport.requestDump);
Log.d("test", "response: " + androidHttpTransport.responseDump);
SoapObject resultsRequestSOAP = (SoapObject) soapEnvelope.bodyIn;
String c = resultsRequestSOAP.toString();
} catch (Exception e) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, e.getMessage(), duration);
toast.show();
toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
}
}
My Java web service Code:
package MyPackage;
public class WebServiceClass {
public String addnumbers(String[] a, String b) {
String c = new StringBuilder("This the String1 ").append(a[0]).append(" merged with String2 ").append(b).toString();
return c;
}
}
My Globals:
private static final String NAMESPACE = "http://MyPackage"; private
static final String URL =
"http://10.0.2.2:8080/WebService/services/WebServiceClass?wsdl"; private
static final String SOAP_ACTION = "urn:addnumbers"; private static final
String METHOD_NAME = "addnumbers";
Issue:
The response I receive is:
addnumbersResponse{return=This the String1 merged with String2 my name; }
The first parameter is not being sent to web service. I have tried to remove this line:
soapEnvelope.dotNet = false; but its still not working.
Guys please help me out. I am stuck for two days. Thanks for any help provided.
Your method's first argument's type is String array, not only String. Instead of StringArraySerializer, please try adding strings manually. You should see this page for this: Adding an array of complex objects to the request.
Check if your namespace is right!
I spent three hours with the same problem and only then realized that the namespace that was declared in the WebService class was different from what I put in the creation of SoapObject.

Categories