以登陆为例,代码如下:
//从EditText控件中获取填入的内容 String username = fieldusername.getText().toString(); String password = fieldpassword.getText().toString(); //设置要访问的命名空间,WebService地址和WebService调用的方法名 //android模拟器访问本地Tomcat上部署的WebService时,不能使用localhost或本机IP,android默认访问本地地址是10.0.2.2 String NAMESPACE = "http://services.crm.nova.org/"; String SERVICEURL = "http://10.0.2.2:8080/CRM/services/userservice"; String method_name = "loginUser"; String WebMethod = NAMESPACE + method_name; //为SOAP对象指定命名空间和方法名 SoapObject rpc = new SoapObject(NAMESPACE, method_name); //设置调用方法的参数值,如果没有参数,可以省略。 要注意的是,参数必须和服务声明的@WebParam里面的变量名对应 rpc.addProperty("username", username); rpc.addProperty("password", password); //生成调用Webservice方法的SOAP请求信息。该信息由SoapSerializationEnvelope对象描述 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = rpc; envelope.dotNet = false; envelope.setOutputSoapObject(rpc); //创建HttpTransportsSE对象。通过AndroidHttpTransport类的构造方法可以指定WebService的WSDL文档的URL HttpTransportSE htse = new HttpTransportSE(SERVICEURL); htse.debug = true; try { htse.call(WebMethod, envelope); if(envelope.getResponse()!=null){ SoapObject object = (SoapObject) envelope.bodyIn; TblUser tblUser = parseTblUser(object); Intent intent = new Intent(); intent.setClass(AndroidCRM.this, UserView.class); Bundle bundle = new Bundle(); bundle.putSerializable("KEY_TBLUSER", tblUser); intent.putExtras(bundle); startActivity(intent); }else{ Toast.makeText(AndroidCRM.this, "用户名或密码错误", Toast.LENGTH_LONG).show(); } } catch (IOException e) { e.printStackTrace(); Toast.makeText(AndroidCRM.this, e.getMessage(), Toast.LENGTH_LONG).show(); } catch (XmlPullParserException e) { e.printStackTrace(); Toast.makeText(AndroidCRM.this, e.getMessage(), Toast.LENGTH_LONG).show(); }
NAMESPACE要看服务器端的WSDL文件获取,ServiceUrl就是将访问WebService的地址中的localhost用10.0.2.2这个ip来替换掉,envelope.dotNet这个值如果不是调用.Net的WebService最好设置成false,否则有可能参数那报错。
注意:从服务器端返回来的数据并不是我们期望的可序列化的对象,而是字符串,需要自己写方法(parseTblUser(object))来解析,这里只返回一个对象还比较简单,当返回集合的时候就会比较复杂了。