Unity3d請求webservice


  我們在對接第三方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,其中theCityCode和theUserID是參數和上面的post方式一樣。好了,輪到我們的unity3d上場了。

  我們先用unity畫出我們需要的效果,因為我們要做一個天氣預報的小程序,我們可以先畫個藍天的背景,在做幾個動態的雲朵,以達到美化的效果。效果如圖:

新建一個腳本,並綁定到Canvas上我們的雲朵就滾動起來了。

YunScroll.cs

using UnityEngine;
using System.Collections;

public class YunScroll : MonoBehaviour
{
    private const int bg_w = 937;
    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);
        if (yun1.position.x <= -(bg_w / 2))
        {
            yun1.position = new Vector3(bg_w + (bg_w / 2), yun1.position.y, yun1.position.z);
        }

        //
        yun2.Translate(Vector3.left * Time.deltaTime * mSpeed);
        if (yun2.position.x <= -(bg_w / 2))
        {
            yun2.position = new Vector3(bg_w + (bg_w / 2), 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()
    {
        for (int i = 0; i < panels.Length; ++i)
        {
            Transform[] objs = new Transform[4];

            objs[0] = panels[i].transform.FindChild("Day");
            objs[1] = panels[i].transform.FindChild("Temperature");
            objs[2] = panels[i].transform.FindChild("Wind");
            objs[3] = 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[0].InnerXml,
            childNode[4].InnerXml,
            childNode[5].InnerXml);

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

        for (int i = 0; i < contextDic.Count; ++i)
        {
            contextDic[i][0].GetComponent<Text>().text = childNode[7 + i * 5].InnerXml;
            contextDic[i][1].GetComponent<Text>().text = childNode[8 + i * 5].InnerXml;
            contextDic[i][2].GetComponent<Text>().text = childNode[9 + i * 5].InnerXml;

            string str = string.Format("a_{0}", childNode[10 + i * 5].InnerXml.Split('.')[0]);
            Sprite sp = Resources.Load(str, typeof(Sprite)) as Sprite;
            if (sp != null)
            {
                contextDic[i][3].GetComponent<Image>().sprite = sp;
            }
        }
    }
}

 

綁定物體到腳本對應的變量,給按鈕添加事件響應,好了,我們一個簡單的天氣預報應用搞出來了,我們看看效果吧。

模擬器上運行

轉載請注明出處:http://www.cnblogs.com/fyluyg/p/6047819.html

下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM