Unity: POST request using WWW class using JSON

后端 未结 4 1484
情话喂你
情话喂你 2021-01-07 01:18

I am trying to make a POST request to restful web APIs in Unity.

The header would be Content-Type: application/json

An example of the raw data i

相关标签:
4条回答
  • 2021-01-07 01:37

    If you want to add raw json data it is better to just pass it without WWWForm

    public WWW POST()
    {
        WWW www;
        Hashtable postHeader = new Hashtable();
        postHeader.Add("Content-Type", "application/json");
    
        // convert json string to byte
        var formData = System.Text.Encoding.UTF8.GetBytes(jsonStr);
    
        www = new WWW(POSTAddUserURL, formData, postHeader);
        StartCoroutine(WaitForRequest(www));
        return www;
    }
    
    0 讨论(0)
  • 2021-01-07 01:38

    I've done for doing this below. Let's go : ==>

    using UnityEngine;
    
    using UnityEngine.UI;
    
    using System.Collections;
    
    using System.Collections.Generic;
    
    public class btnGetData : MonoBehaviour {
    
     void Start()
     {
         gameObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
     }
     IEnumerator WaitForWWW(WWW www)
     {
         yield return www;
    
    
         string txt = "";
         if (string.IsNullOrEmpty(www.error))
             txt = www.text;  //text of success
         else
             txt = www.error;  //error
         GameObject.Find("Txtdemo").GetComponent<Text>().text =  "++++++\n\n" + txt;
     }
     void TaskOnClick()
     {
         try
         {
             GameObject.Find("Txtdemo").GetComponent<Text>().text = "starting..";   
             string ourPostData = "{\"plan\":\"TESTA02\"";
             Dictionary<string,string> headers = new Dictionary<string, string>();
             headers.Add("Content-Type", "application/json");
             //byte[] b = System.Text.Encoding.UTF8.GetBytes();
             byte[] pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
             ///POST by IIS hosting...
             WWW api = new WWW("http://192.168.1.120/si_aoi/api/total", pData, headers);
             ///GET by IIS hosting...
             ///WWW api = new WWW("http://192.168.1.120/si_aoi/api/total?dynamix={\"plan\":\"TESTA02\"");
             StartCoroutine(WaitForWWW(api));
         }
         catch (UnityException ex) { Debug.Log(ex.Message); }
     }
    
    }
    
    0 讨论(0)
  • 2021-01-07 01:40
    private void SendJson(string url, string json)
    {
        StartCoroutine(PostRequestCoroutine(url, json, callback));
    }
    
    private IEnumerator PostRequestCoroutine(string url, string json)
    {
        var jsonBinary = System.Text.Encoding.UTF8.GetBytes(json);    
    
        DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();
    
        UploadHandlerRaw uploadHandlerRaw = new UploadHandlerRaw(jsonBinary);
        uploadHandlerRaw.contentType = "application/json";
    
        UnityWebRequest www = 
            new UnityWebRequest(url, "POST", downloadHandlerBuffer, uploadHandlerRaw);
    
        yield return www.SendWebRequest();
    
        if (www.isNetworkError)
            Debug.LogError(string.Format("{0}: {1}", www.url, www.error));
        else
           Debug.Log(string.Format("Response: {0}", www.downloadHandler.text));
    }
    
    0 讨论(0)
  • 2021-01-07 01:49
    try {
        string url_registerEvent = "http://demo....?parameter1=" parameter1value"&parameter2="parameter2value;
    
        WebRequest req = WebRequest.Create (url_registerEvent);
        req.ContentType = "application/json";
        req.Method = "SET";
        //req.Credentials = new NetworkCredential ("connect10@gmail.com", "connect10api");
        HttpWebResponse resp = req.GetResponse () as HttpWebResponse;
    
        var encoding = resp.CharacterSet == ""
                    ? Encoding.UTF8
                    : Encoding.GetEncoding (resp.CharacterSet);
    
        using (var stream = resp.GetResponseStream ()) {
            var reader = new StreamReader (stream, encoding);
            var responseString = reader.ReadToEnd ();
    
            Debug.Log ("Result :" + responseString);
            //JObject json = JObject.Parse(str);
        }
    } catch (Exception e) {
        Debug.Log ("ERROR : " + e.Message);
    }
    
    0 讨论(0)
提交回复
热议问题