Unity的WWW是基於HTTP協議的網絡傳輸功能,使用HTTP協議傳輸數據有多種方式,Unity的WWW主要支持其中的GET與POST方式。GET方式會將請求附加在URL後,POST方式則是經過FORM的形式提交,GET方式最多能傳遞1024個字節,POST方式理論上沒有限制。從安全角度來看POST比GET方式安全性更高,因此在實際使用中能夠更多選擇POST方式。 html
下面爲你們簡單介紹一下Unity中WWW的簡單使用方法。java
1.GET請求web
IEnumerator JavaGet()
{
WWW www = new WWW("http://localhost:8080/web_02/myservlet?username=aaxx&password=ccoo");
yield return www;
if (www.error == null)
{
string str = www.text;
Debug.Log("消息長度:" + str.Length + "消息內容爲:" + str);
}
else
{
Debug.Log("GET請求出錯");
}安全
}服務器
2.POST請求 網絡
IEnumerator JavaPost()
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/xx");
string data = "username=stt&password=wxy";
byte[] bs = Encoding.UTF8.GetBytes(data);
WWW www = new WWW("http://localhost:8080/web_02/myservlet", bs, headers);
yield return www;
if(www.error != null)
{
Debug.Log(www.error);
yield return null;
}
Debug.Log(www.text);
}app
服務器端用的是JavaServlet編碼
package stt.javaa.servlet;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;htm
@WebServlet("/myservlet")
public class myservlet extends HttpServlet {圖片
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設置返回消息的編碼格式
response.setCharacterEncoding("utf-8");
//設置html的編碼格式
response.setContentType("text/html; charset=utf-8");
//返回給Unity的消息
response.getWriter().append("GET 請求成功");
//向控制檯輸出
System.out.println("客戶端GET請求");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設置返回消息的編碼格式
response.setCharacterEncoding("utf-8");
//設置html的編碼格式
response.setContentType("text/html; charset=utf-8");
//返回給Unity的消息
response.getWriter().append("POST 請求成功");
//向控制檯輸出
System.out.println("客戶端POST請求");
//輸出請求頭
System.out.println(request.getHeader("Content-Type"));
}
}
Tip:若是直接複製使用須要把包名更改
3.下載圖片
IEnumerator GetImage()
{
WWW www = new WWW("http://localhost/stt/image.png");
yield return www;
if (www.error == null)
{
Texture2D tex = www.texture;
GameObject.Find("Cube").GetComponent<MeshRenderer>().material.mainTexture = tex;
}
}
4.下載音樂
IEnumerator GetMusic(){ WWW www = new WWW("http://localhost/stt/bhsd.wav"); yield return www; if(www.error == null) { AudioClip clip = www.GetAudioClip(false); } }