Unity:使用JSON使用WWW类的POST请求

时间:2016-06-29 20:40:46

标签: c# rest post unity3d request

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

标题为Content-Type: application/json

原始数据输入的一个示例是,其中data是键,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类发送请求?或者,一般来说,我该如何发送这种帖子请求?

4 个答案:

答案 0 :(得分:7)

如果要添加原始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;
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

SelectedDeviceActivity

答案 3 :(得分:-2)

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

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

}