天天看點

Unity3D 網絡通信_HTTP協定:擷取網絡圖檔、内容

自己寫的測試demo,一個功能一個功能測試着做的,沒有什麼結構,湊合看吧。

http協定,在手機平台,URL必須必帶http://頭。

此腳本主要實作了 

分别用pose和get方式擷取天氣預報資訊(XML格式)。

解析XML

擷取網絡圖檔

擷取網絡圖檔(base64格式)

base64與byte[]互轉

byte[]與Texture2D(圖檔)互轉

using UnityEngine;  

using System.Collections;  

using System.Collections.Generic;  

using System.Xml;  

using System.IO;  

public class HTTPDemo : MonoBehaviour  

{  

    public string HostName = "http://www.webxml.com.cn";  

    //城市天氣預報服務   

    public string URLPath = "/WebServices/WeatherWebService.asmx/getWeatherbyCityName";  

    //獲得驗證碼服務(直接獲得圖檔)  

    private string PictureName = "/WebServices/ValidateCodeWebService.asmx/cnValidateImage?byString='Picture'";  

    //獲得驗證碼服務(獲得圖檔位元組流)  

    private string PictureByteName = "/WebServices/ValidateCodeWebService.asmx/cnValidateByte?byString='picByte'";  

    private Texture2D mPicture;  

    private Texture2D mPictureByte;  

    private Texture2D mConvertPNG;  

    public string[] Parameters = new string[] { "theCityName" };  

    private string XMLContent = "null";  

    public string testC = "null";  

    void OnGUI()  

    {  

        //顯示測試資訊   

        GUI.Label(new Rect(100, 10, 1000, 38), testC);  

        //表單傳值  

        if (GUI.Button(new Rect(10, 50, 100, 60), "post"))  

        {  

            postWeatherbyCityName("北京");  

        }  

        GUI.Button(new Rect(120, 80, 100 + getJindu() * 100, 20), (getJindu() * 100) + "%");  

        //get傳值(android平台不支援中文參數)  

        if (GUI.Button(new Rect(10, 130, 100, 60), "get"))  

            getWeatherbyCityName("58367");//上海  

        GUI.Button(new Rect(120, 150, 100 + getJindu() * 100, 20), (getJindu() * 100) + "%");  

        //顯示讀取到的天氣預報原始資訊(xml格式)  

        GUI.Label(new Rect(10, 220, 380, 500), mContent);  

        //解析xml   

        if (GUI.Button(new Rect(500, 200, 120, 60), "AnalysisXML"))  

            XMLContent = AnalysisXML();  

        GUI.Label(new Rect(410, 220, 380, 500), XMLContent);  

        //下載下傳網絡圖檔   

        if (GUI.Button(new Rect(10, 750, 80, 60), "downPic"))  

            downloadPicture(PictureName);  

        GUI.Label(new Rect(100, 760, 200, 200), mPicture);  

        //下載下傳網絡圖檔 (base64格式)  

        if (GUI.Button(new Rect(350, 750, 80, 60), "downPicByte"))  

            downloadPictureByte(PictureByteName);  

        GUI.Label(new Rect(450, 760, 200, 200), mPictureByte);  

    }  

    public void postWeatherbyCityName(string str)  

        //将參數集合封裝到Dictionary集合友善傳值  

        Dictionary<string, string> dic = new Dictionary<string, string>();  

        //參數  

        dic.Add(Parameters[0], str);  

        StartCoroutine(POST(HostName + URLPath , dic));  

    public void getWeatherbyCityName(string str)  

        StartCoroutine(GET(HostName + URLPath , dic));  

    //下載下傳圖檔   

    public void downloadPicture(string picName)  

        testC ="picurl = " + picName;  

        StartCoroutine(GETTexture(HostName + picName));  

    //下載下傳圖檔(位元組流)  

    public void downloadPictureByte(string picName)  

        StartCoroutine(GETTextureByte(HostName + picName));  

    /*----------------------------------------------------Helper----------------------------------------------------------------------------*/  

    private float mJindu = 0;  

    private string mContent;  

    public float getJindu()  

        return mJindu;  

    //POST請求(Form表單傳值、效率低、安全 ,)  

    IEnumerator POST(string url, Dictionary<string, string> post)  

        //表單   

        WWWForm form = new WWWForm();  

        //從集合中取出所有參數,設定表單參數(AddField()).  

        foreach (KeyValuePair<string, string> post_arg in post)  

            form.AddField(post_arg.Key, post_arg.Value);  

        //表單傳值,就是post   

        WWW www = new WWW(url, form);  

        yield return www;  

        mJindu = www.progress;  

        if (www.error != null)  

            //POST請求失敗  

            mContent =  "error :" + www.error;  

        else  

            //POST請求成功  

            mContent = www.text;  

    //GET請求(url?傳值、效率高、不安全 )  

    IEnumerator GET(string url, Dictionary<string, string> get)  

        string Parameters;  

        bool first;  

        if (get.Count > 0)  

            first = true;  

            Parameters = "?";  

            //從集合中取出所有參數,設定表單參數(AddField()).  

            foreach (KeyValuePair<string, string> post_arg in get)  

            {  

                if (first)  

                    first = false;  

                else  

                    Parameters += "&";  

                Parameters += post_arg.Key + "=" + post_arg.Value;  

            }  

            Parameters = "";  

        testC ="getURL :" + Parameters;  

        //直接URL傳值就是get  

        WWW www = new WWW(url + Parameters);  

            //GET請求失敗  

            mContent = "error :" + www.error;  

            //GET請求成功  

    IEnumerator GETTexture(string picURL)  

        WWW wwwTexture = new WWW(picURL);  

        yield return wwwTexture;  

        if (wwwTexture.error != null)  

            Debug.Log("error :" + wwwTexture.error);  

            mPicture = wwwTexture.texture;  

    string PicByte;  

    IEnumerator GETTextureByte(string picURL)  

        WWW www = new WWW(picURL);  

            Debug.Log("error :" + www.error);  

            Debug.Log("PicBytes text = " + www.text);  

            XmlDocument xmlDoc = new XmlDocument();  

            xmlDoc.Load(new StringReader(www.text));  

            //通過索引查找子節點   

            PicByte = xmlDoc.GetElementsByTagName("base64Binary").Item(0).InnerText;  

            testC = PicByte;  

            mPictureByte = BttetoPic(PicByte);  

    //解析XML   

    string AnalysisXML()  

        string str = "";  

        XmlDocument xmlDoc = new XmlDocument();  

        xmlDoc.Load(new StringReader(mContent));  

        //得到文檔根節點的所有子節點集合   

        //XmlNodeList nodes = xmlDoc.DocumentElement.ChildNodes;  

        //通過節點名得到節點集合  

        XmlNodeList nodes = xmlDoc.GetElementsByTagName("string");  

        //通過索引查找子節點   

        str += "item[1] = " + xmlDoc.GetElementsByTagName("string").Item(1).InnerText + "\n\n";  

        //周遊所有子節點  

        foreach (XmlElement element in nodes)  

            if (element.Name == "string")  

                str += element.InnerText + "\n";  

        return str;  

    //圖檔與byte[]互轉  

    public void convertPNG(Texture2D pic)  

        byte[] data = pic.EncodeToPNG();  

        Debug.Log("data = " + data.Length + "|" + data[0]);  

        mConvertPNG = new Texture2D(200, 200);  

        mConvertPNG.LoadImage(data);  

    //byte[]與base64互轉   

    Texture2D BttetoPic(string base64)  

    {   

        Texture2D pic = new Texture2D(200,200);  

        //将base64轉碼為byte[]   

        byte[] data = System.Convert.FromBase64String(base64);  

        //加載byte[]圖檔  

        pic.LoadImage(data);  

        string base64str = System.Convert.ToBase64String(data);  

        Debug.Log("base64str = " + base64str);  

        return pic;  

}  

本文轉蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366243,如需轉載請自行聯系原作者