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

本文关键字:JSON WWW 请求 Unity POST | 更新日期: 2023-09-27 17:53:07

我正在尝试在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类的形式和头?或者,一般来说,我如何发送这种post request?

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

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

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

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