Android调用WCF(一)
Android调用WCF(一)
2013-05-16 11:03:47
在最近的项目开发中需要与WCF服务端进行交互,通过学习总结了一下Android调用WCF的方法。
这里主要是介绍用的第三方包Ksoap2来进行的交互。
先从最简单的传递字符串开始。代码如下:
1、建立一个ISoapService接口
1 public interface ISoapService { 2 SoapObject loadResult(); 3 }
2、建立与WCF进行交互的类HelloService
1 public class HelloService implements ISoapService { 2 3 private static final String NameSpace = "http://tempuri.org/"; 4 private static final String URL = "http://172.16.201.190:8015/Service.svc"; //请求URL 5 private static final String SOAP_ACTION = "http://tempuri.org/IServer/GetStu"; 6 private static final String MethodName = "GetStu"; 7 8 private String Name; 9 private String Age; 10 11 12 public HelloService(String name,String age) { 13 this.Name = name; 14 this.Age = age; 15 } 16 public HelloService() { 17 } 18 19 public SoapObject loadResult() { 20 SoapObject soapObject = new SoapObject(NameSpace, MethodName); 21 // 添加属性 22 soapObject.addProperty("Name", Name); 23 soapObject.addProperty("Age", Age); 24 25 26 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // 版本 27 envelope.bodyOut = soapObject;//不要忘了设置 SoapSerializationEnvelope类的bodyOut属性,该属性的值就是在第1步创建的SoapObject对象。 28 envelope.dotNet = true;//设置与.Net提供的Web Service保持较好的兼容性 29 envelope.setOutputSoapObject(soapObject); 30 31 HttpTransportSE trans = new HttpTransportSE(URL);//指定HttpTransportSE 32 trans.debug = true; // 使用调试功能 33 34 try { 35 trans.call(SOAP_ACTION, envelope);//访问webservice服务器 36 System.out.println("Call Successful!"); 37 } catch (IOException e) { 38 System.out.println("IOException"); 39 e.printStackTrace(); 40 } catch (XmlPullParserException e) { 41 System.out.println("XmlPullParserException"); 42 e.printStackTrace(); 43 } 44 45 46 SoapObject result = (SoapObject) envelope.bodyIn; //获取服务器返回的信息 47 48 return result; 49 } 50 51 }
代码中的NameSpace是指命名空间,URL是你要交互的网址,MethodName是你要调用服务端的方法名。
soapObject.addProperty("Name", Name)方法中的第一个参数书服务端对应属性的名字,第二个参数是自己这里定义的名字。
3、Android代码:
1 public class AndroidWcfDemoActivit extends Activity { 2 private Button mButton1; 3 private TextView text; 4 5 /** Called when the activity is first created. */ 6 @Override 7 public void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_android_wcf_demo); 10 mButton1 = (Button) findViewById(R.id.myButton1); 11 text = (TextView) this.findViewById(R.id.show); 12 13 mButton1.setText(R.string.inquire); 14 15 mButton1.setOnClickListener(new Button.OnClickListener() { 16 @Override 17 public void onClick(View v) { 18 19 20 HelloService service = new HelloService("jdh","21"); 21 SoapObject result = service.loadResult(); 22 if(result != null) 23 text.setText("WCF返回的数据是:" + result.getProperty(0)); 24 25 } 26 }); 27 } 28 }
通过以上方法的调用,服务端会收到我发送的信息,并可以返回信息给我。不过这里只能实现简单的字符串传递和接收。若是要接收到来自服务端的集合类中的信息,需要进一步的了解Ksoap2包。在下一篇中将着重接收接收来自服务端的集合类中信息的方法。

浙公网安备 33010602011771号