import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;

public class CallWs extends Activity {
  final static String SERVICE_NS = "http://lee/";
  final static String SERVICE_URL = "http://172.18.5.198/crazyit";
  private EditText text1;
  private EditText text2;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_call_ws);
    text1 = (EditText) findViewById(R.id.text1);
    text2 = (EditText) findViewById(R.id.text2);
    //调用的方法
    String methodName = "getUserList";
    //创建HttpTransportSE传输对象
    HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
    ht.debug = true;
    //使用SOAP1.1协议创建Envelop对象
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    //实例化SoapObject对象
    SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
    soapObject.addProperty("arg0","客户端参数:");
    //将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
    envelope.bodyOut = soapObject;
    try {
      //调用Web Service
      ht.call(null, envelope);
      if(envelope.getResponse() != null){
        //获取服务器响应返回的SOAP消息
        SoapObject result = (SoapObject) envelope.bodyIn;
        //接下来是从SoapObject对象中解析响应数据的过程
        SoapObject detail1 = (SoapObject) result.getProperty(0);
        SoapObject detail2 = (SoapObject) result.getProperty(1);
        StringBuilder person1 = new StringBuilder();
        person1.append("用户名:");
        person1.append(detail1.getProperty(3));
        person1.append("\n密码");
        person1.append(detail1.getProperty(0));
        person1.append("\n身高");
        person1.append(detail1.getProperty(1));
        text1.setText(person1.toString());
        StringBuilder person2 = new StringBuilder();
        person2.append("用户名:");
        person2.append(detail2.getProperty(3));
        person2.append("\n密码");
        person2.append(detail2.getProperty(0));
        person2.append("\n身高");
        person2.append(detail2.getProperty(1));
        text2.setText(person2.toString());
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (XmlPullParserException e) {
      e.printStackTrace();
    }
  }

}

上面程序中的粗体字代码就代表了使用ksoap2-android来调用Web  Service操作的关键的7个步骤。

不管远程Web  Service提供的服务功能多么强大、业务实现多么复杂,对于Android客户端是完全透明的,Android只要送出相应的请求参数,服务器就会返回包含结果的SOAP消息。借助于Web  Service这个桥梁,在Android应用中实现功能非常强大的应用-----反正具体的业务逻辑由Web Service服务器实现,Android客户端只要调用Web  Service服务即可。

posted on 2016-07-06 09:17  奋斗青年一族  阅读(289)  评论(0编辑  收藏  举报