Android访问Web service

Android需要连接利用.Net编写的Web service服务器端程序,Android自身并不支持Web service,工程中进入第三方的jar(http://code.google.com/p/ksoap2-android/)解决了问题。

主要代码如下:

private static final String METHOD_NAME = "Login";
private static final String SOAP_ACTION = "http://tempuri.org/"+METHOD_NAME;
private static final String NAMESPACE = "http://tempuri.org/";   
private static final String URL = "http://192.168.0.111/testserver/AuthService.asmx";

public void loginServer() throws Exception  {
   
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo propertyInfo = new PropertyInfo();
    propertyInfo.setName("username");
    propertyInfo.setValue("zhangsan");           
    request.addProperty(propertyInfo);
   
    propertyInfo = new PropertyInfo();
    propertyInfo.setName("password");
    propertyInfo.setValue("1234");           
    request.addProperty(propertyInfo);

    SoapSerializationEnvelope envelope =
        new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
   
    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    androidHttpTransport.call(SOAP_ACTION, envelope);
   
    SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
    Log.v("tag", "the soap result is >>>>>"+result.toString());

}


private static final String METHOD_NAME = "Login";

Login为需要连接的web端方法名。

private static final String NAMESPACE = "http://tempuri.org/"; 

http://tempuri.org是SOAP规范,必须这样写。

private static final String URL= "http://192.168.0.111/testserver/AuthService.asmx";

为服务器端URL。

PropertyInfo propertyInfo = new PropertyInfo();
    propertyInfo.setName("username");
    propertyInfo.setValue("zhangsan");           
    request.addProperty(propertyInfo);
   
    propertyInfo = new PropertyInfo();
    propertyInfo.setName("password");
    propertyInfo.setValue("1234");           
    request.addProperty(propertyInfo);

需要向服务器端传递的参数,这里是username和password。


SoapSerializationEnvelope envelope =
        new SoapSerializationEnvelope(SoapEnvelope.VER11);

声明遵守SOAP1.1规范。

envelope.dotNet = true;

服务器端为.NET Web service。

SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

获取服务器端返回结果。

你可能感兴趣的:(web Service)