统一:通过使用JSON WWW类POST请求 [英] Unity: POST request using WWW class using JSON

查看:111
本文介绍了统一:通过使用JSON WWW类POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个POST请求,在Unity基于REST的Web API的

I am trying to make a POST request to restful web APIs in Unity.

标题是内容类型:应用程序/ JSON

The header would be Content-Type: application/json

的原始数据输入的一个实例是,其中数据是关键和JSON字符串值:

An example of the raw data input is, where data is the key and json string is the value:

{数据: {用户名:姓名,电子邮件:email@gmail.com,AGE_RANGE:21,性别:男,位置:加州}}

{"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类既发送请求形成和头?或者,只是一般,怎么我发这种帖子的要求?

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

推荐答案

如果你想添加的原始JSON数据它为更好地只是通过它无需 WWWForm

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

这篇关于统一:通过使用JSON WWW类POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆