Unity3D 网络通信_HTTP协议:获取网络图片、内容

简介:

自己写的测试demo,一个功能一个功能测试着做的,没有什么结构,凑合看吧。

http协议,在手机平台,URL必须必带http://头。

此脚本主要实现了 

  • 分别用pose和get方式获取天气预报信息(XML格式)。
  • 解析XML
  • 获取网络图片
  • 获取网络图片(base64格式)
  • base64与byte[]互转
  • byte[]与Texture2D(图片)互转

更多常用WEBService:http://www.webxml.com.cn/zh_cn/web_services.aspx

  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Xml;  
  5. using System.IO;  
  6.   
  7. public class HTTPDemo : MonoBehaviour  
  8. {  
  9.     public string HostName = "http://www.webxml.com.cn";  
  10.     //城市天气预报服务   
  11.     public string URLPath = "/WebServices/WeatherWebService.asmx/getWeatherbyCityName";  
  12.     //获得验证码服务(直接获得图片)  
  13.     private string PictureName = "/WebServices/ValidateCodeWebService.asmx/cnValidateImage?byString='Picture'";  
  14.     //获得验证码服务(获得图片字节流)  
  15.     private string PictureByteName = "/WebServices/ValidateCodeWebService.asmx/cnValidateByte?byString='picByte'";  
  16.           
  17.     private Texture2D mPicture;  
  18.     private Texture2D mPictureByte;  
  19.     private Texture2D mConvertPNG;  
  20.   
  21.     public string[] Parameters = new string[] { "theCityName" };  
  22.   
  23.     private string XMLContent = "null";  
  24.   
  25.     public string testC = "null";  
  26.   
  27.     void OnGUI()  
  28.     {  
  29.         //显示测试信息   
  30.         GUI.Label(new Rect(100, 10, 1000, 38), testC);  
  31.   
  32.   
  33.         //表单传值  
  34.         if (GUI.Button(new Rect(10, 50, 100, 60), "post"))  
  35.         {  
  36.             postWeatherbyCityName("北京");  
  37.         }  
  38.         GUI.Button(new Rect(120, 80, 100 + getJindu() * 100, 20), (getJindu() * 100) + "%");  
  39.   
  40.   
  41.         //get传值(android平台不支持中文参数)  
  42.         if (GUI.Button(new Rect(10, 130, 100, 60), "get"))  
  43.         {  
  44.             getWeatherbyCityName("58367");//上海  
  45.         }  
  46.         GUI.Button(new Rect(120, 150, 100 + getJindu() * 100, 20), (getJindu() * 100) + "%");  
  47.   
  48.   
  49.    
  50.         //显示读取到的天气预报原始信息(xml格式)  
  51.         GUI.Label(new Rect(10, 220, 380, 500), mContent);  
  52.   
  53.   
  54.   
  55.         //解析xml   
  56.         if (GUI.Button(new Rect(500, 200, 120, 60), "AnalysisXML"))  
  57.         {  
  58.             XMLContent = AnalysisXML();  
  59.         }  
  60.         GUI.Label(new Rect(410, 220, 380, 500), XMLContent);  
  61.   
  62.   
  63.   
  64.         //下载网络图片   
  65.         if (GUI.Button(new Rect(10, 750, 80, 60), "downPic"))  
  66.         {  
  67.             downloadPicture(PictureName);  
  68.         }  
  69.         GUI.Label(new Rect(100, 760, 200, 200), mPicture);  
  70.   
  71.   
  72.         //下载网络图片 (base64格式)  
  73.         if (GUI.Button(new Rect(350, 750, 80, 60), "downPicByte"))  
  74.         {  
  75.             downloadPictureByte(PictureByteName);  
  76.         }  
  77.         GUI.Label(new Rect(450, 760, 200, 200), mPictureByte);  
  78.     }  
  79.   
  80.     public void postWeatherbyCityName(string str)  
  81.     {  
  82.         //将参数集合封装到Dictionary集合方便传值  
  83.         Dictionary<stringstring> dic = new Dictionary<stringstring>();  
  84.   
  85.         //参数  
  86.         dic.Add(Parameters[0], str);  
  87.   
  88.         StartCoroutine(POST(HostName + URLPath , dic));  
  89.     }  
  90.   
  91.     public void getWeatherbyCityName(string str)  
  92.     {  
  93.         //将参数集合封装到Dictionary集合方便传值  
  94.         Dictionary<stringstring> dic = new Dictionary<stringstring>();  
  95.   
  96.         //参数  
  97.         dic.Add(Parameters[0], str);  
  98.   
  99.         StartCoroutine(GET(HostName + URLPath , dic));  
  100.     }  
  101.   
  102.     //下载图片   
  103.     public void downloadPicture(string picName)  
  104.     {  
  105.         testC ="picurl = " + picName;  
  106.   
  107.         StartCoroutine(GETTexture(HostName + picName));  
  108.     }  
  109.   
  110.     //下载图片(字节流)  
  111.     public void downloadPictureByte(string picName)  
  112.     {  
  113.         StartCoroutine(GETTextureByte(HostName + picName));  
  114.     }  
  115.   
  116.     /*----------------------------------------------------Helper----------------------------------------------------------------------------*/  
  117.   
  118.     private float mJindu = 0;  
  119.     private string mContent;  
  120.   
  121.     public float getJindu()  
  122.     {  
  123.         return mJindu;  
  124.     }  
  125.   
  126.     //POST请求(Form表单传值、效率低、安全 ,)  
  127.     IEnumerator POST(string url, Dictionary<stringstring> post)  
  128.     {  
  129.         //表单   
  130.         WWWForm form = new WWWForm();  
  131.         //从集合中取出所有参数,设置表单参数(AddField()).  
  132.         foreach (KeyValuePair<stringstring> post_arg in post)  
  133.         {  
  134.             form.AddField(post_arg.Key, post_arg.Value);  
  135.         }  
  136.         //表单传值,就是post   
  137.         WWW www = new WWW(url, form);  
  138.   
  139.         yield return www;  
  140.         mJindu = www.progress;  
  141.   
  142.         if (www.error != null)  
  143.         {  
  144.             //POST请求失败  
  145.             mContent =  "error :" + www.error;  
  146.         }  
  147.         else  
  148.         {  
  149.             //POST请求成功  
  150.             mContent = www.text;  
  151.         }  
  152.     }  
  153.   
  154.     //GET请求(url?传值、效率高、不安全 )  
  155.     IEnumerator GET(string url, Dictionary<stringstringget)  
  156.     {  
  157.         string Parameters;  
  158.         bool first;  
  159.         if (get.Count > 0)  
  160.         {  
  161.             first = true;  
  162.             Parameters = "?";  
  163.             //从集合中取出所有参数,设置表单参数(AddField()).  
  164.             foreach (KeyValuePair<stringstring> post_arg in get)  
  165.             {  
  166.                 if (first)  
  167.                     first = false;  
  168.                 else  
  169.                     Parameters += "&";  
  170.   
  171.                 Parameters += post_arg.Key + "=" + post_arg.Value;  
  172.             }  
  173.         }  
  174.         else  
  175.         {  
  176.             Parameters = "";  
  177.         }  
  178.   
  179.         testC ="getURL :" + Parameters;  
  180.   
  181.         //直接URL传值就是get  
  182.         WWW www = new WWW(url + Parameters);  
  183.         yield return www;  
  184.         mJindu = www.progress;  
  185.   
  186.         if (www.error != null)  
  187.         {  
  188.             //GET请求失败  
  189.             mContent = "error :" + www.error;  
  190.         }  
  191.         else  
  192.         {  
  193.             //GET请求成功  
  194.             mContent = www.text;  
  195.         }  
  196.     }  
  197.   
  198.     IEnumerator GETTexture(string picURL)  
  199.     {  
  200.         WWW wwwTexture = new WWW(picURL);  
  201.   
  202.         yield return wwwTexture;  
  203.   
  204.         if (wwwTexture.error != null)  
  205.         {  
  206.             //GET请求失败  
  207.             Debug.Log("error :" + wwwTexture.error);  
  208.         }  
  209.         else  
  210.         {  
  211.             //GET请求成功  
  212.             mPicture = wwwTexture.texture;  
  213.         }  
  214.     }  
  215.   
  216.     string PicByte;  
  217.     IEnumerator GETTextureByte(string picURL)  
  218.     {  
  219.         WWW www = new WWW(picURL);  
  220.   
  221.         yield return www;  
  222.   
  223.         if (www.error != null)  
  224.         {  
  225.             //GET请求失败  
  226.             Debug.Log("error :" + www.error);  
  227.         }  
  228.         else  
  229.         {  
  230.             //GET请求成功  
  231.             Debug.Log("PicBytes text = " + www.text);  
  232.   
  233.             XmlDocument xmlDoc = new XmlDocument();  
  234.             xmlDoc.Load(new StringReader(www.text));  
  235.   
  236.             //通过索引查找子节点   
  237.             PicByte = xmlDoc.GetElementsByTagName("base64Binary").Item(0).InnerText;  
  238.             testC = PicByte;  
  239.   
  240.             mPictureByte = BttetoPic(PicByte);  
  241.         }  
  242.     }  
  243.   
  244.     //解析XML   
  245.     string AnalysisXML()  
  246.     {  
  247.         string str = "";  
  248.   
  249.         XmlDocument xmlDoc = new XmlDocument();  
  250.         xmlDoc.Load(new StringReader(mContent));  
  251.   
  252.         //得到文档根节点的所有子节点集合   
  253.         //XmlNodeList nodes = xmlDoc.DocumentElement.ChildNodes;  
  254.         //通过节点名得到节点集合  
  255.         XmlNodeList nodes = xmlDoc.GetElementsByTagName("string");  
  256.   
  257.         //通过索引查找子节点   
  258.         str += "item[1] = " + xmlDoc.GetElementsByTagName("string").Item(1).InnerText + "\n\n";  
  259.   
  260.         //遍历所有子节点  
  261.         foreach (XmlElement element in nodes)  
  262.         {  
  263.             if (element.Name == "string")  
  264.             {  
  265.                 str += element.InnerText + "\n";  
  266.             }  
  267.         }  
  268.           
  269.         return str;  
  270.     }  
  271.   
  272.     //图片与byte[]互转  
  273.     public void convertPNG(Texture2D pic)  
  274.     {  
  275.         byte[] data = pic.EncodeToPNG();  
  276.         Debug.Log("data = " + data.Length + "|" + data[0]);  
  277.         mConvertPNG = new Texture2D(200, 200);  
  278.         mConvertPNG.LoadImage(data);  
  279.     }  
  280.   
  281.     //byte[]与base64互转   
  282.     Texture2D BttetoPic(string base64)  
  283.     {   
  284.         Texture2D pic = new Texture2D(200,200);  
  285.         //将base64转码为byte[]   
  286.         byte[] data = System.Convert.FromBase64String(base64);  
  287.         //加载byte[]图片  
  288.         pic.LoadImage(data);  
  289.   
  290.         string base64str = System.Convert.ToBase64String(data);  
  291.         Debug.Log("base64str = " + base64str);  
  292.   
  293.         return pic;  
  294.     }  
  295. }  




















本文转蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366243,如需转载请自行联系原作者






相关文章
|
15天前
|
缓存 网络协议 前端开发
Web 性能优化|了解 HTTP 协议后才能理解的预加载
本文旨在探讨和分享多种预加载技术及其在提升网站性能、优化用户体验方面的应用。
Web 性能优化|了解 HTTP 协议后才能理解的预加载
|
21天前
|
XML JSON 前端开发
HTTP协议,Content-Type格式介绍篇
通过理解和正确使用Content-Type头字段,可以确保数据在网络上传输时的正确性和高效性,提升网络应用的可靠性和用户体验
92 28
|
19天前
|
XML JSON 前端开发
HTTP协议,Content-Type格式介绍篇
通过理解和正确使用Content-Type头字段,可以确保数据在网络上传输时的正确性和高效性,提升网络应用的可靠性和用户体验。
141 25
|
22天前
|
XML JSON 前端开发
HTTP协议,Content-Type格式介绍篇
通过理解和正确使用Content-Type头字段,可以确保数据在网络上传输时的正确性和高效性,提升网络应用的可靠性和用户体验。
192 18
|
2月前
|
域名解析 缓存 网络协议
Web基础与HTTP协议
通过掌握这些基础知识和技术,开发者可以更加高效地构建和优化Web应用,提供更好的用户体验和系统性能。
79 15
|
2月前
|
前端开发 网络协议 安全
【网络原理】——HTTP协议、fiddler抓包
HTTP超文本传输,HTML,fiddler抓包,URL,urlencode,HTTP首行方法,GET方法,POST方法
|
2月前
|
网络协议 安全 网络安全
探索网络模型与协议:从OSI到HTTPs的原理解析
OSI七层网络模型和TCP/IP四层模型是理解和设计计算机网络的框架。OSI模型包括物理层、数据链路层、网络层、传输层、会话层、表示层和应用层,而TCP/IP模型则简化为链路层、网络层、传输层和 HTTPS协议基于HTTP并通过TLS/SSL加密数据,确保安全传输。其连接过程涉及TCP三次握手、SSL证书验证、对称密钥交换等步骤,以保障通信的安全性和完整性。数字信封技术使用非对称加密和数字证书确保数据的机密性和身份认证。 浏览器通过Https访问网站的过程包括输入网址、DNS解析、建立TCP连接、发送HTTPS请求、接收响应、验证证书和解析网页内容等步骤,确保用户与服务器之间的安全通信。
125 3
|
2月前
|
缓存 网络协议 算法
从零开始掌握HTTP协议
本文介绍HTTP协议的演变,从HTTP1.0到HTTP2.0。HTTP1.0为无状态连接,每次请求独立;HTTP1.1引入持久连接、管道化请求和更多状态码;HTTP2.0采用二进制分帧、多路复用、头部压缩及服务器主动推送,大幅提升性能与用户体验。了解这些区别有助于开发者优化应用和服务。
|
3月前
|
安全 搜索推荐 网络安全
HTTPS协议是**一种通过计算机网络进行安全通信的传输协议
HTTPS协议是**一种通过计算机网络进行安全通信的传输协议
89 11
|
3月前
|
监控 网络协议 网络性能优化
网络通信的核心选择:TCP与UDP协议深度解析
在网络通信领域,TCP(传输控制协议)和UDP(用户数据报协议)是两种基础且截然不同的传输层协议。它们各自的特点和适用场景对于网络工程师和开发者来说至关重要。本文将深入探讨TCP和UDP的核心区别,并分析它们在实际应用中的选择依据。
91 3