Unity新的网络请求方式UnityWebRequest(5.2版本以后)

Get方式:

  1. private IEnumerator SendUrl(string url)
  2. {
  3. using (UnityWebRequest www = UnityWebRequest.Get(url))
  4. {
  5. yield return www.Send();
  6. if (www.error != null)
  7. {
  8. Debug.Log(www.error);
  9. }
  10. else
  11. {
  12. if (www.responseCode == 200)//200表示接受成功
  13. {
  14. Debug.Log(www.downloadHandler.text);
  15. }
  16. }
  17. }
  18. }

Post方式:

  1. public IEnumerator PostUrl(string url, string postData)
  2. {
  3. using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
  4. {
  5. byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
  6. www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
  7. www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  8. www.SetRequestHeader("Content-Type", "application/json");
  9. yield return www.Send();
  10. if (www.isError)
  11. {
  12. Debug.Log(www.error);
  13. }
  14. else
  15. {
  16. // Show results as text
  17. if (www.responseCode == 200)
  18. {
  19. Debug.Log(www.downloadHandler.text);
  20. }
  21. }
  22. }
  23. }
  24. private IEnumerator PostUrl(string url, WWWForm form, Action<string> getResult)
  25. {
  26. using (UnityWebRequest www = UnityWebRequest.Post(url, form))
  27. {
  28. yield return www.Send();
  29. if (www.isError)
  30. {
  31. yield return www.error;
  32. }
  33. else
  34. {
  35. if (www.responseCode == 200)
  36. {
  37. getResult(www.downloadHandler.text);
  38. }
  39. }
  40. }
  41. }
(0)

相关推荐