Unity新的网络请求方式UnityWebRequest(5.2版本以后)
Get方式:
private IEnumerator SendUrl(string url)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.error != null)
{
Debug.Log(www.error);
}
else
{
if (www.responseCode == 200)//200表示接受成功
{
Debug.Log(www.downloadHandler.text);
}
}
}
}
Post方式:
public IEnumerator PostUrl(string url, string postData)
{
using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
{
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
if (www.responseCode == 200)
{
Debug.Log(www.downloadHandler.text);
}
}
}
}
private IEnumerator PostUrl(string url, WWWForm form, Action<string> getResult)
{
using (UnityWebRequest www = UnityWebRequest.Post(url, form))
{
yield return www.Send();
if (www.isError)
{
yield return www.error;
}
else
{
if (www.responseCode == 200)
{
getResult(www.downloadHandler.text);
}
}
}
}
赞 (0)