Unity WWW
Unity 的WWW 主要支持其中的GET和POST方式。
GET 方式会将请求附加在URL后,POST 方式则是通过FORM (表单)的形式提交。
GET方式最多只能传输1024个字节,POST方式理论上则没有限制。从安全角度来看POST比GET方式安全性更高,所以在实际使用中可以更多选择POST方式。
具体例子如下:
- 文本格式上传
IEnumerator IGetData()
{
WWW www = new WWW(''http://127.0.0 . 1/test.php?username=get&password=12345");
yield return www;
if (www.error != null)
{
m info = www.error;
yield return null;
}
m info = www.text;
}
IEnumerator IPostData ()
{
//headers 是一个Hashtable ,它由键、值对应,这里我们用它来保存HTTP报头。
System.Collections.Hashtable headers = new System.Collections.Hashtable();
headers.Add("Content-Type", "application/x-www-form-urlencoded");
string data = "username=post&password=6789"; //和Get一样使用&连接数据
byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes(data); //转化为byte 数组
WWW www = new WWW("http://127.0.0.1/test.php'', bs, headers);
yield return www;
if (www.error != null)
{
m_info = www.error;
yield return null;
}
m_info = www.text;
}
- 图片格式
public Texture2D m_uploadImage;
protected Texture2D m_downloadTexture;
IEnumerator IRequestPNG()
{
byte[] bs = m_uploadImage.EncodeToPNG();
WWWForm form = new WWWForm();
form.AddBinaryData("picture" , bs, "screenshot", "image/png");
WWW www = new WWW( ''http://127.0.0.1/Test.php'', form);
yield return www;
if (www.error != null)
{
m_info = www.error;
yield return null;
}
m_downloadTexture = www.texture; //返回文本信息
}
//显示下载的图片和提交的图片:
OnGUI()
{
if (m_downloadTexture != null)
GUI.DrawTexture(new Rect(0, 0, m_downloadTexture.width, m_downloadTexture.height), m_downloadTexture);
if(GUI.Button(new Rect(10, 150, 150, 30), "Request Image"))
StartCoroutine(IRequestPNG());
}