Unity: POST request using WWW class using JSON

2019-04-15 08:11发布

问题:

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 input is, where data is the key and json string is the value:

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

Here's my script:

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

How do I send the request using WWW class with both form and header? Or, just in general, how do I send this kind of post request?

回答1:

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


回答2:

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


回答3:

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


回答4:

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

}