unity中UnityWebRequest和WWW都可以实现HTTP请求,下面举例说明两种方法分别实现Get和Post请求
1、UnityWebRequest实现HTTP请求
Get请求
IEnumerator GetRequest(string url)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
if (!string.IsNullOrEmpty(webRequest.error))
{
Debug.LogError(webRequest.error);
}
else
{
Debug.Log(webRequest.downloadHandler.text);
}
}
}
Post请求
IEnumerator PostRequest(string url)
{
WWWForm form = new WWWForm();
form.AddField("name", "posttest");
using (UnityWebRequest webRequest = UnityWebRequest.Post(url, form))
{
yield return webRequest.SendWebRequest();
if (!string.IsNullOrEmpty(webRequest.error))
{
Debug.LogError(webRequest.error);
}