Unity的WWW是基于HTTP协议的网络传输功能,使用HTTP协议传输数据有多种方式,Unity的WWW主要支持其中的GET与POST方式。GET方式会将请求附加在URL后,POST方式则是通过FORM的形式提交,GET方式最多能传递1024个字节,POST方式理论上没有限制。从安全角度来看POST比GET方式安全性更高,所以在实际使用中可以更多选择POST方式。
下面为大家简单介绍一下Unity中WWW的简单使用方法。
1.GET请求
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);
}
服务器端用的是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;
@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);
}
}