Unity3D requests WebService

When we dock a third-party SDK, the third-party SDK will usually be called by us in the form of a webservice interface. And these interfaces will provide us with get, post, soap and other protocols for access. I believe everyone is familiar with the get and post methods. Today we will focus on the access to the soap protocol.

  soap, also known as Simple Object Access Protocol, is a protocol specification for exchanging data, and soap is based on xml. The three elements of webService include one of SOAP, WSDL, and UDDI. Soap is used to describe the format of information transmission, WSDL is used to describe how to access specific interfaces, and uddi is used to manage, distribute, and query webService. SOAP can be combined with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Multipurpose Internet Mail Extension Protocol (MIME). It also supports a large number of applications ranging from messaging systems to remote procedure calls (RPC). SOAP uses a combination of XML-based data structures and Hypertext Transfer Protocol (HTTP) to define a standard method to use distributed objects in various operating environments on the Internet. For more information, you can refer to related materials online. For soap and wsdl tutorials, you can see SOAP and WSDL.

   Let’s make an example of requesting a weather forecast. The webservice interface for free weather forecast testing is provided on the Internet, but there is a limit on the number of times it can be used per day. For more interface information, please visit http://www.webxml.com.cn/zh_cn/index.aspx. Check http://www.webxml.com.cn/zh_cn/index.aspx to find the “getWeather” interface we need for weather forecasts. We can see that this interface provides post, get and soap access methods. Our small program uses post and soap access methods, so we have to look at the post and soap usage methods it provides.

  < /p>

   This is the way to use post. We initiate a webservice with theCityCode=string&theUserID=string is fine. Where theCityCode is the city name such as “Shenzhen”, or Shenzhen’s corresponding code “2419”, cannot be empty. theUserID is the member id, it can be empty, and it is free to use. The following is the return from the request, which is a character array in the form of xml.

  

   This is the way to use soap access, we construct an xml soap through soap access, where theCityCode and theUserID are the same as the above post method. Well, it’s our turn to play unity3d.

  , let’s use unity to draw the effect we need, because we are going to make a small program for weather forecast, we can draw a blue sky background first, and make a few dynamic clouds to achieve beautification Effect. The effect is shown in the figure:

Create a new script, bind it to Canvas, and our clouds will roll.

YunScroll.cs

copy code
using UnityEngine;using System.Collections;public span> class YunScroll: MonoBehaviour{ private const int bg_w = ​​937; private const float mSpeed ​​= 30.0f ; Transfo rm yun1; Transform yun2; // Use this for initialization void Start() {yun1 = transform.FindChild("yun1"); Debug.Assert(yun1 != null, "Object not found"); yun2  = transform.FindChild("yun2"); Debug.Assert(yun2 != null , "Object not found");} // 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< span style="line-height:1.5!important">), yun2.position.y, yun2.position.z);} }}
copy code < /div>

  Okay, our sky cloud background has moved, and we will add content and picture space to display the weather. The effect is shown in the figure:

Add the script WeatherScript and bind it to the main camera.

WeatherScript.cs:

copy code
using UnityEngine;usin g 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 < span style="color:rgb(0,0,255); line-height:1.5!important">void Start() {< span style="color:rgb(0,0,255); line-height:1.5!important">for (int i = 0; i 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() {} ///  /// post call///  public void OnPost() {StartCoroutine(PostHandler());} ///  /// soap call///   public void OnSoap() {StartCoroutine(SoapHandler());} IEnumerator PostHandler() {WWWForm form =  new WWWForm(); form.AddField("theCityCode", "Shenzhen"); 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("" ); soap.Append(" "); soap.Append(" "); soap.Append(""); soap.Append("Shenzhen"); soap.Append(""); soap.Append(""); soap.Append ("" ); soap.Append(" "); WWWForm form = new WWWForm(); var headers = form.headers; headers["Content-Type< /span>"] = "text/xml; charset=utf-8< /span>"; headers[ "SOAPAction"] = "http://WebXml.com.cn/getWeather"; headers["User-Agent"] = "gSOAP/2.8"< /span>; WWW w = new< /span> WWW("http://ws.webxml.c om.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, Reque st_Type.SOAP);}}} private void ParsingXml(string _xml,Request_Type _type) {XmlDocument xmlDoc = new< /span> 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< /span> (_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 = String.Format("{0} . {1},{2}", childNode[0].InnerXml, childNode[4].InnerXml, childNode[5].InnerXml); toDayInfo.GetComponent().text = childNode[6].InnerXml; for (int i = 0; i i)        {            contextDic[i][0].GetComponent().text = childNode[7 + i * 5].InnerXml;            contextDic[i][1].GetComponent().text = childNode[8 + i * 5].InnerXml;            contextDic[i][2].GetComponent().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().sprite = sp;            }        }    }}
复制代码

 

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

模拟器上运行

转载自:http://www.cnblogs.com/fyluyg/p/6047819.html

复制代码
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("< span style="color:rgb(128,0,0); line-height:1.5!important">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);        }    }}
复制代码

复制代码

复制代码

复制代码
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 text Asset = (TextAsset)Resources.Load("weather_2");//         ParsingXml(textAsset.text, Request_Type.SOAP);    }    // Update is called once per frame    void Update()    {    }    ///     /// post调用    ///     public void OnPost()    {        StartCoroutine(PostHandler());    }    ///     /// soap调用    ///     public void OnSoa p()    {        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("");        soap.Append("");        soap.Append("");        soap.Append("");        soap.Append("深圳");        soap.Append("");        soap.Append("");        soap.Append("");        soap.Append("");        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 arrO fStr = xmlDoc.DocumentElement;        XmlNodeList childNode = null;        #region POST        if (_type == Request_Type.POST)        {            childNode = arrOfStr.ChildNodes;        }        #endregion        #region SOAP        else if (_type == Request_Type.SOAP)        {            xmlDo c.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 = String.Format("{0}。 {1},{2}",            childNode[0].InnerXml,            childNode[4].InnerXml,            childNode[5].InnerXml);        toDayInfo.GetComponent().text = childNode[6].InnerXml;        for (int i = 0; i < cont extDic.Count; ++i)        {            contextDic[i][0].GetComponent().text = childNode[7 + i * 5].InnerXml;            contextDic[i][1].GetComponent().text = childNode[8 + i * 5].InnerXml;            contextDic[i][2].GetComponent().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().sprite = sp;            }        }    }}
复制代码

< span class="cnblogs_code_copy" style="padding-right:5px; line-height:1.5!important">复制代码

复制代码

Leave a Comment

Your email address will not be published.