andorid使用ksoap2进行WebService通信

WebService 是一种基于SOAP协议的远程调用标准。通过WebService可以将不同操作系统平台,不同语言、不同技术整合到一起。在Android SDK中并没有提供调用WebService的库,因此,需要使用第三方类库(KSOAP2)来调用WebService。

示例代码分为两部分,android端与Web端(Android studio,VS2015)

  • Web端

使用VS创建一个新项目,选择Visual C# –> web –>ASP.NET Web应用程序,在资源管理器中打开后缀为.asmx文件进行修改

代码部分:

namespace WebService1
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello";
        }
        [WebMethod]
        public string[] EchoMessage(string msg1,string msg2)
        {
            string []name = { msg1, msg2 };
            return name;
        }
    }
}
  • android端(在AndroidManifest文件中添加网络连接权限)

Android端demo分为三个文件:MainActivity.java,Nettask.java,Netsetting.java

MainActivity.java:加载布局文件提高测试效果
Nettask.java:Ksoap2包的使用,进行网络通信
Netsetting.java:网络通信基本设置信息

MainActivity.java主要代码展示:

private void initBtn() {
      //初始化按钮点击事件
      View btnHelloWorld = this.findViewById(R.id.btnHelloWorld);
      btnHelloWorld.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {

              Map<String, String> values = new HashMap<String, String>();
              //设置参数
              values.put("msg", "It's android data");
              //发出请求
              Request(mNetSetting.getMethod_Hello());
          }
      });

      View btnEchoMessage = this.findViewById(R.id.btnEchoMessage);
      btnEchoMessage.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
              Map<String, String> values = new HashMap<String, String>();
              //设置参数
              values.put("msg1", "It's android data one");
              values.put("msg2", "It's android data two");
              //发出请求
              Request(mNetSetting.getMethod_Echo(), values);
          }
      });
  }

  /*
  * Push Request for WebService
  * 使用AsyncTask完成网络通信(直接放入主线程会直接报错)
  */
  public void Request(Object... params) {
      new AsyncTask<Object, Object, String>() {
          //Change the Textview content
          String txt=new String();
          @Override
          protected String doInBackground(Object... params) {
              if (params != null && params.length == 2) {
                  txt= mNetTask.Distribute_WebService((String) params[0],
                          (Map<String, String>) params[1]);
              } else if (params != null && params.length == 1) {
                  txt= mNetTask.Distribute_WebService((String) params[0], null);
              } else {
                  return null;
              }
              return null;
          }

          protected void onPostExecute(String result) {
              //在主页面的Textview显示返回信息
              tvMessage.setText("Information from Server : " + txt);
          };
      }.execute(params);
  }

Nettask.java代码展示:

public class NetTask {

    private NetSetting mNetSetting=new NetSetting();

    //initialize the Method in Package "ksoap2" and get the object form SoapSerializationEnvelope
    //初始化方法ksoap包中的方法(如果是单纯使用不需要明白下面的意思,类似一个模板的使用)
    public SoapSerializationEnvelope DoGet(String MethodName, Map<String, String> Params){
        // 1、Define the WebService Space name and Method
        SoapObject request = new SoapObject(mNetSetting.getNamespace()  , MethodName);
        //Set the Method's parameter if not exists then ignore it
        //获取从MainActivity内的request方法中的参数,以及参数类型
        if (Params != null) {
            Iterator iter = Params.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                request.addProperty((String) entry.getKey(),
                        (String) entry.getValue());
            }
        }
        /*
         *   3、Create and use Webservice method to generate soap request
         *      parameter is the vserion name of Soap protocol and you can check it's Instructions to know it(eg:WebService1.asmx?WSDL)
         *   3、创建并且使用Webservice方法产生请求
         *      new SoapSerializationEnvelope(SoapEnvelope.VER12)方法中的VER12为soap协议的版本号
         */
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER12);
        envelope.bodyOut = request;
        // when you use donet protocol then use true
        envelope.dotNet = true;
        //envelope为WEBSERVICE传输内容
        HttpTransportSE http = new HttpTransportSE(mNetSetting.getURL());
        // use call() to connect Server
        // call()方法实际为连接服务器
        try {
            http.call(null, envelope);
        } catch (HttpResponseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        return envelope;
    }

    //Change Method according to the MethodName
    //根据请求选择不同的方法
    public String Distribute_WebService(String MethodName, Map<String, String> Params){
        if(MethodName.equals(mNetSetting.getMethod_Hello()))
            return Hello_CallWebService(MethodName,Params);
        else{
            return Echo_CallWebService(MethodName,Params);
        }
    }


    //Hello_CallWebService
    public String Hello_CallWebService(String MethodName, Map<String, String> Params) {
        SoapSerializationEnvelope envelope=DoGet(MethodName,Params);
        try {
            //单个数据选择SoapPrimitive
            final SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
            if (result!= null) {
                Log.d("----ReceivedMessage----", result.toString());
                return result.toString();
            }

        } catch (SoapFault e) {
            Log.e("----WrongMessage---", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    //Echo_CallWebService
    public String Echo_CallWebService(String MethodName, Map<String, String> Params) {
        SoapSerializationEnvelope envelope=DoGet(MethodName,Params);
        try{
            //复杂数据选择SoapObject
            final SoapObject result = (SoapObject) envelope.getResponse();
            if (result!= null) {
                //通过使用getProperty()方法可以实现调用传输过来的方法
                Log.d("----ReceivedMessage----", result.getProperty(0).toString());
                Log.d("----ReceivedMessage----", result.getProperty(1).toString());
                return result.toString();
            }

        } catch (SoapFault e) {
            Log.e("----WrongMessage---", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}

Netsetting.java:

public class NetSetting {

    public NetSetting(){};

    //Method Name 值与Web端相应方法的值必须保持一致
    final String METHOD_HELLO_WORLD = "HelloWorld";
    final String METHOD_ECHO_MESSAGE = "EchoMessage";

    //Server Url
    final String WEB_SERVICE_URL = "http://ip/WebService1.asmx";
    //WebService Space Name
    final String Namespace = "http://tempuri.org/";
    //Get Space Name
    public String getNamespace(){
        return Namespace;
    }
    //Get WebService Url
    public String getURL(){
        return WEB_SERVICE_URL;
    }
    //Get Mthod Name "HelloWorld"
    public String getMethod_Hello(){
        return METHOD_HELLO_WORLD;
    }
    //Get Mthod Name "EchoMessage"
    public String getMethod_Echo(){
        return METHOD_ECHO_MESSAGE;
    }
}

这里为全代码的demo地址
http://download.csdn.net/detail/enough_empty/9628832
git 地址
https://github.com/yclog/ksoap2-webservice-demo

参考博客
还是你最好:http://www.cnblogs.com/gzggyy/archive/2011/06/21/2086140.html

__Ps:博主使用了各种手段设置WEB_SERVICE_URL中的IP都以android端连接失败告终,最后因为时间关系强行将web服务发布到服务器上,才解决了这个问题
之前尝试改为http://10.0.2.2/WebService1.asmx 仍旧存在问题,如果有博友在本地成功希望能留下评论交流,谢谢__

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值