【问题标题】:Unity: POST request using WWW class using JSONUnity:使用 JSON 的 WWW 类 POST 请求
【发布时间】:2016-06-29 20:40:46
【问题描述】:

我正在尝试向 Unity 中的 RESTful Web API 发出 POST 请求。

标题为Content-Type: application/json

原始数据输入的一个例子是,其中数据是键,json字符串是值:

{  
   "data":{  
      "username":"name",
      "email":"email@gmail.com",
      "age_range":21,
      "gender":"male",
      "location":"california"
   }
}

这是我的脚本:

private static readonly string POSTAddUserURL = "http://db.url.com/api/addUser";
public WWW POST()
{
    WWW www;
    Hashtable postHeader = new Hashtable();
    postHeader.Add("Content-Type", "application/json");
    WWWForm form = new WWWForm();
    form.AddField("data", jsonStr);
    www = new WWW(POSTAddUserURL, form);
    StartCoroutine(WaitForRequest(www));
    return www;
}

IEnumerator WaitForRequest(WWW data)
{
    yield return data; // Wait until the download is done
    if (data.error != null)
    {
        MainUI.ShowDebug("There was an error sending request: " + data.error);
    }
    else
    {
        MainUI.ShowDebug("WWW Request: " + data.text);
    }
}

如何使用WWW 类发送请求,同时包含表单和标题?或者,一般来说,我如何发送这种发布请求?

【问题讨论】:

  • 使用新的 WWW(url, form.data, postHeader);

标签: c# rest post unity3d request


【解决方案1】:

如果你想添加原始 json 数据,最好不通过 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;
}

【讨论】:

  • 有效!! :D 你只是拯救了我的一天。非常感谢
【解决方案2】:
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));
}

【讨论】:

    【解决方案3】:
    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);
    }
    

    【讨论】:

      【解决方案4】:

      我已经在下面这样做了。走吧:==>

      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); }
       }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-10
        • 2017-09-26
        • 2014-03-30
        • 2018-03-24
        • 1970-01-01
        • 2016-07-28
        • 1970-01-01
        • 2016-12-03
        相关资源
        最近更新 更多