Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Unity: POST request using WWW class using JSON

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 protected]",
      "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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...