我们在对接第三方sdk时,第三方sdk通常会以一个webservice接口的形式供我们来调用。而这些接口会以提供我们get,post,soap等协议来进行访问。get,post方法相信大家都比较熟悉了,今天我们着重讨论soap协议的访问。

  soap又叫简单对象访问协议,是交换数据的一种协议规范,soap是基于xml的。webService三要素就包含SOAP、WSDL、UDDI之一, soap用来描述传递信息的格式, WSDL 用来描述如何访问具体的接口, uddi用来管理,分发,查询webService 。SOAP 可以和现存的许多因特网协议和格式结合使用,包括超文本传输协议(HTTP),简单邮件传输协议(SMTP),多用途网际邮件扩充协议(MIME)。它还支持从消息系统到远程过程调用(RPC)等大量的应用程序。SOAP使用基于XML的数据结构和超文本传输协议(HTTP)的组合定义了一个标准的方法来使用Internet上各种不同操作环境中的分布式对象。更多的信息大家可以网上参考相关资料,soap和wsdl的教程可以看SOAP,WSDL

  下面我们来做一个请求天气预报的例子。网上提供了天气预报免费测试的webservice接口,不过每天有使用次数限制。更多的接口信息可以访问http://www.webxml.com.cn/zh_cn/index.aspx。查看http://www.webxml.com.cn/zh_cn/index.aspx找到我们天气预报需要的"getWeather"接口,我们可以看到这个接口提供post,get和soap的访问方法。我们这个小程序用到post和soap的访问方法,所以我们要看他提供的post和soap的使用方式。

  

  这个是post的使用方式,我们向webservice发起带theCityCode=string&theUserID=string的参数请求就可以了。其中theCityCode为城市名称比如"深圳",或者深圳对应的code"2419",不能为空。theUserID是会员id,可以为空,为空则是免费使用。下面的是请求返回,它是一个xml形式的字符数组。

  

  这是soap访问的使用方式,我们通过soap访问构造一个xml的soap

  我们先用unity画出我们需要的效果,因为我们要做一个天气预报的小程序,我们可以先画个蓝天的背景,在做几个动态的云朵,以达到美化的效果。效果如图:

新建一个脚本,并绑定到Canvas上我们的云朵就滚动起来了。

YunScroll.cs

using UnityEngine;
using System.Collections;

public class YunScroll : MonoBehaviour
{
    ;
    private const float mSpeed = 30.0f;
    Transform yun1;
    Transform yun2;

    // Use this for initialization
    void Start()
    {
        yun1 = transform.FindChild("yun1");
        Debug.Assert(yun1 != null, "对象找不到");

        yun2 = transform.FindChild("yun2");
        Debug.Assert(yun2 != null, "对象找不到");

       }

    // Update is called once per frame
    void Update()
    {
        //
        yun1.Translate(Vector3.left * Time.deltaTime * mSpeed);
        ))
        {
            yun1.position = ), yun1.position.y, yun1.position.z);
        }

        //
        yun2.Translate(Vector3.left * Time.deltaTime * mSpeed);
        ))
        {
            yun2.position = ), yun2.position.y, yun2.position.z);
        }
    }
}

  好了,我们的天空云朵背景已经动起来了,我们再添加显示天气的内容和图片空间。效果如图:

添加脚本WeatherScript并绑定到主摄像机上。

WeatherScript.cs:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;
using System.Xml;
using UnityEngine.UI;

public class WeatherScript : MonoBehaviour
{
    enum Request_Type
    {
        POST,
        SOAP,
    }

    public Text title;
    public Text toDayInfo;
    public GameObject[] panels;

    private Dictionary<int, Transform[]> contextDic = new Dictionary<int, Transform[]>();

    // Use this for initialization
    void Start()
    {
        ; i < panels.Length; ++i)
        {
            Transform[] objs = ];

            objs[] = panels[i].transform.FindChild("Day");
            objs[] = panels[i].transform.FindChild("Temperature");
            objs[] = panels[i].transform.FindChild("Wind");
            objs[] = panels[i].transform.FindChild("Image");

            contextDic[i] = objs;
        }

//         TextAsset textAsset = (TextAsset)Resources.Load("weather_2");
//         ParsingXml(textAsset.text, Request_Type.SOAP);
    }

    // Update is called once per frame
    void Update()
    {

    }

    /// <summary>
    /// post调用
    /// </summary>
    public void OnPost()
    {
        StartCoroutine(PostHandler());
    }

    /// <summary>
    /// soap调用
    /// </summary>
    public void OnSoap()
    {
        StartCoroutine(SoapHandler());
    }

    IEnumerator PostHandler()
    {
        WWWForm form = new WWWForm();

        form.AddField("theCityCode", "深圳");
        form.AddField("theUserID", "");

        WWW w = new WWW("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather", form);

        yield return w;

        if (w.isDone)
        {
            if (w.error != null)
            {
                print(w.error);
            }
            else
            {
                ParsingXml(w.text, Request_Type.POST);
            }
        }
    }

    IEnumerator SoapHandler()
    {
        StringBuilder soap = new StringBuilder();

        soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soap.Append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
        soap.Append("<soap12:Body>");
        soap.Append("<getWeather xmlns=\"http://WebXml.com.cn/\">");
        soap.Append("<theCityCode>深圳</theCityCode>");
        soap.Append("<theUserID></theUserID>");
        soap.Append("</getWeather>");
        soap.Append("</soap12:Body>");
        soap.Append("</soap12:Envelope>");

        WWWForm form = new WWWForm();
        var headers = form.headers;

        headers["Content-Type"] = "text/xml; charset=utf-8";
        headers["SOAPAction"] = "http://WebXml.com.cn/getWeather";
        headers["User-Agent"] = "gSOAP/2.8";

        WWW w = new WWW("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx", Encoding.UTF8.GetBytes(soap.ToString()), headers);
        yield return w;
        if (w.isDone)
        {
            if (w.error != null)
            {
                print(w.error);
            }
            else
            {
                ParsingXml(w.text, Request_Type.SOAP);
            }
        }
    }

    private void ParsingXml(string _xml,Request_Type _type)
    {
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.LoadXml(_xml);

        XmlNode arrOfStr = xmlDoc.DocumentElement;
        XmlNodeList childNode = null;

        #region POST
        if (_type == Request_Type.POST)
        {
            childNode = arrOfStr.ChildNodes;
        }
        #endregion
        #region SOAP
        else if (_type == Request_Type.SOAP)
        {
            xmlDoc.LoadXml(arrOfStr.InnerXml);
            arrOfStr = xmlDoc.DocumentElement;
            xmlDoc.LoadXml(arrOfStr.InnerXml);
            arrOfStr = xmlDoc.DocumentElement;
            xmlDoc.LoadXml(arrOfStr.InnerXml);
            arrOfStr = xmlDoc.DocumentElement;
            childNode = arrOfStr.ChildNodes;
        }
        #endregion

        title.GetComponent<Text>().text = String.Format("<color=red>{0}</color>。{1},{2}",
            childNode[].InnerXml,
            childNode[].InnerXml,
            childNode[].InnerXml);

        toDayInfo.GetComponent<Text>().text = childNode[].InnerXml;

        ; i < contextDic.Count; ++i)
        {
            contextDic[i][].GetComponent<Text>().text = childNode[ + i * ].InnerXml;
            contextDic[i][].GetComponent<Text>().text = childNode[ + i * ].InnerXml;
            contextDic[i][].GetComponent<Text>().text = childNode[ + i * ].InnerXml;

             + i * ].InnerXml.Split(]);
            Sprite sp = Resources.Load(str, typeof(Sprite)) as Sprite;
            if (sp != null)
            {
                contextDic[i][].GetComponent<Image>().sprite = sp;
            }
        }
    }
}

绑定物体到脚本对应的变量,给按钮添加事件响应,好了,我们一个简单的天气预报应用搞出来了,我们看看效果吧。

模拟器上运行

转载请注明出处:http://www.cnblogs.com/fyluyg/p/6047819.html

下载

Unity3d请求webservice的更多相关文章

  1. jquery+ajax跨域请求webservice

    最近几天在学习webservice...在学习的时候便想到用ajax的方式去请求webservice.. 一直在测试..如果这个被请求的webservice和自己使用的是同一个端口号.则不用考虑那aj ...

  2. Node.js 使用 soap 模块请求 WebService 服务接口

    项目开发中需要请求webservice服务,前端主要使用node.js 作为运行环境,因此可以使用soap进行请求. 使用SOAP请求webservice服务的流程如下: 1.进入项目目录,安装 so ...

  3. JQuery请求WebService返回数据的几种处理方式

    打开自己的博客仔细浏览了一番,发现已经好久没有写博客了,由于最近一直比较忙碌懈怠了好多.默默反省三分钟.......言归正传,现在就对最近在学习webservice的过程中遇到的几种类型的问题中我的理 ...

  4. ajax请求webservice时抛出终止线程的异常

    请求webservice中以下接口,会抛出异常 {"Message":"正在中止线程.","StackTrace":" 在 Sys ...

  5. webserive学习记录6-页面请求webservice

    前面都是通过JAVA代码访问webservice服务,下面将介绍通过javascript,jquery访问webservice服务并介绍过过servlet解决跨域问题的方法. 服务端 编写服务代码,解 ...

  6. 通过HttpClient请求webService

    通过HttpClient请求webService 由于服务端是用webService开发的,android要调用webService服务获取数据,这里采用的是通过HttpClient发送post请求, ...

  7. Kettle通过Http post请求webservice接口以及结果解析处理

    kettle中有两种方式请求webservice服务,一个是Web服务查询,但是这个有缺陷,无法处理复杂的需求,遇到这种情况就需要用Http post来处理了. 网上也有很多关于Http post请求 ...

  8. ajax请求webservice的过程中遇到的问题总结

    前台用ajax的post方法,无法请求到webservice中的方法的时候,需要在配置文件中添加 web.config文件中的 <system.web> 节点下加入:<webServ ...

  9. AJAX请求WebService

    1.WebService代码 [WebMethod] [ScriptMethod(UseHttpGet = false)] public string GetObject() { User user ...

随机推荐

  1. NoSql数据库使用

    NoSql数据库使用半年后在设计上面的一些心得 NoSql数据库这个概念听闻许久了,也陆续看到很多公司和产品都在使用,优缺点似乎都被分析的清清楚楚.但我心里一直存有一个疑惑,它的出现究竟是为了解决什么 ...

  2. c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

    c#实现Google账号登入授权(OAuth 2.0)并获取个人信息   此博主要介绍通过google 账号(gmail)实现登入,授权方式OAuth2.0,下面我们开始介绍. 1.去google官网 ...

  3. VMware上安装ubuntu 13.04

    作者:viczzx 出处:http://www.cnblogs.com/zixuan-zhang 欢迎转载,也请保留这段声明.谢谢! 这两天打算在Linux环境下学Python语言,想换个高点的ubu ...

  4. SharePoint SPHierarchyDataSourceControl+SPTreeView

    今天使用SPHierarchyDataSourceControl和SPTreeView来显示SharePoint文档库层级结构的过程中,发现一直在报下面的错误: The target 'ctl00$c ...

  5. EasyUI实现异步加载tree(整合Struts2)

    首先jsp页面有一ul用于展现Tree <ul id="mytree"></ul> 加载Tree <script type="text/ja ...

  6. No object in the CompoundRoot has a publicly accessible property named

    No object in the CompoundRoot has a publicly accessible property named 'typeid' (no setter could be ...

  7. synchronized和volatile的使用

    synchronized和volatile的使用 一步一步掌握线程机制(三)---synchronized和volatile的使用 现在开始进入线程编程中最重要的话题---数据同步,它是线程编程的核心 ...

  8. centos安装svn

    原文链接:http://blog.csdn.net/liuyuan_jq/article/details/2110814 1.SVN简介由于前些年在版本的管理上采用的都是CVS系统,总体上而言还是很优 ...

  9. .NET:国际化和本地化

    .NET:国际化和本地化 背景 国际化(i18n)和本地化(l10n)是高端程序的必备技术,可惜从业五年从没有尝试过,下一步准备做一个多用户的博客系统,想支持多语言,今天就学习了一下,写出来,希望大家 ...

  10. COFF/PE文件结构

    COFF/PE文件结构 原创 C++应用程序在Windows下的编译.链接(二)COFF/PE文件结构 2.1概述 在windows操作系统下,可执行文件的存储格式是PE格式:在Linux操作系统下, ...