最近在做一个项目
主要通过 HTTP 接口来关联 Unity 和 JavaWeb 项目
public IEnumerator GetRequest()
{
// 请求的 url
string url = 你要请求的url地址
// 是什么请求就调用什么方法,如果是 post/put 方法,还需要传递一个 string 类型的数据
// 可以用 JSON 工具类将对象封装成 JSON
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
// 出现网络错误
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
}
else// 正常处理
{
// 获取到的数据
string data = webRequest.downloadHandler.text;
}
}
}
总结来说,主要通过 UnityWebRequest
这个类的 GET、POST、PUT、DELETE 方法来进行 HTTP 交互
只要写好 url 地址即可,在 Java 里是什么 url,在 unity 里就是什么
GET 请求的话,通过 downloadHandler.text
获取返回的数据,可以把它直接输出,或者解析成 JSON 数据,
关于如何解析 JSON 数据,上一篇博客有说,主要用 Newtonsoft.json,因为返回的数据是 JSON,所以自己写好一个实体类,实体类的属性对应 JSON 里的 key 值就可以。
POST 请求也一样,把数据封装成 JSON 发送即可,举例:
private void Start()
{
// 启动协程,通过 POST 请求提交数据
StartCoroutine(PostRequest(new Student(1, "Kobe")));
}
public IEnumerator PostRequest(Student student)
{
string url = "http://localhost:8010/unity/updateStudent";
// 封装学生信息为 JSON 数据
string data = JsonConvert.SerializeObject(student);
Debug.Log("请求的数据:" + data);
using (UnityWebRequest webRequest = UnityWebRequest.Put(url,data))
{
// 设置消息格式为 JSON
webRequest.SetRequestHeader("Content-Type", "application/json");
yield return webRequest.SendWebRequest();
// 出现网络错误
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
}
}
}
// 封装数据的学生类
public class Student
{
public Student(int id,string sname)
{
this.id = id;
this.sname = sname;
}
public int id;
public string sname;
}