JuanJSAR

GetJSON

Feb 28th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.27 KB | None | 0 0
  1. using System.Text;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6.  
  7. public class SendJSON : MonoBehaviour {
  8.  
  9.     IEnumerator Start()
  10.     {
  11.         string Response = null;
  12.         yield return StartCoroutine(SendRequest(@"https://next.json-generator.com/api/json/get/Ey7IuRl88", MethodsHTTP.GET, delegate (bool state, string message) { Response = message; }));
  13.  
  14.         Debug.Log(Response.Length);
  15.         Debug.Log(Response);
  16.     }
  17.  
  18.     public struct Headers { public string name; public string value; }
  19.     public enum MethodsHTTP { GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH };
  20.     public static IEnumerator SendRequest(string url, MethodsHTTP type, System.Action<bool, string> outputMessage, string arguments = "", string json = "", string token = "", UploadHandler handler = null, List<Headers> headers = null)
  21.     {
  22.         Debug.Log(url + arguments);
  23.         //headers.ForEach(delegate (Headers data) { Debug.Log(data.name); Debug.Log(data.value); });
  24.  
  25.         var www = new UnityWebRequest(url + arguments, type.ToString());
  26.         if (handler != null)
  27.         {
  28.             www.uploadHandler = handler;
  29.         }
  30.         else if (!string.IsNullOrEmpty(json))
  31.         {
  32.             byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
  33.             www.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  34.             www.SetRequestHeader("Content-Type", "application/json");
  35.         }
  36.         if (!string.IsNullOrEmpty(token))
  37.         {
  38.             www.SetRequestHeader("Token", token);
  39.         }
  40.         if (headers != null && headers.Count > 0)
  41.         {
  42.             headers.ForEach((x) => www.SetRequestHeader(x.name, x.value));
  43.         }
  44.         www.downloadHandler = new DownloadHandlerBuffer();
  45.  
  46.         yield return www.SendWebRequest();
  47.  
  48.         if (www.isNetworkError || www.isHttpError)
  49.         {
  50.             outputMessage(false, Encoding.UTF8.GetString(www.downloadHandler.data));
  51.             //Debug.Log(Encoding.UTF8.GetString(www.downloadHandler.data));
  52.         }
  53.         else
  54.         {
  55.             //Debug.Log(Encoding.UTF8.GetString(www.downloadHandler.data));
  56.             outputMessage(true, (Encoding.UTF8.GetString(www.downloadHandler.data)));
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment