cURL 命令到 Unity 的 Web 请求



我有一个JSON,其结构如下:

{
"values": {
"AppName": "Test001",
"AppUser": "Testttt"
},
"consentAccepted": true,
"consentToken": "adgrtztzEZKo3LD56Hjo8LiqeoQ2Z5+ik0loplr"
}

上面的JSON在https://web.postman.co/我获得了成功的地位。

我想尝试Unity的WebRequest和POST来填写";AppName";以及";AppUser";以及代币。我该如何做到这一点?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class SendData: MonoBehaviour {
void Update () {
if (InputCompat.GetKeyDown (KeyCode.P)) {
StartCoroutine ("FillAndSend");
}
}
public IEnumerator FillAndSend() {
WWWForm form = new WWWForm ();
form.AddField ("AppName", "Testttt");
form.AddField ("AppUser", "Reinnn");
UnityWebRequest www = UnityWebRequest.Post ("https://mywebsite.com/profile/MyApp", form);
www.SetRequestHeader ("token", "tz677zuiuis2qEZKo3Lt+kHluOGss");
yield return www.SendWebRequest ();
if (www.isNetworkError || www.isHttpError) {
Debug.Log (www.error);
} else {
Debug.Log (www.downloadHandler.text);
}
}
}

我收到一个名为HTTP内部服务器错误的错误。它怎么了?除此之外,我还必须添加一个特定的参数,该参数如下所示:

formToken: MyApp

看起来您更希望发送一个JSON字符串,而不是form

类似的东西

var json = "{"values": {"AppName":"Test001","AppUser":"Rein"}, "consentAccepted":true, "consentToken":"tz677zuiuis2qEZKo3Lt+kHluOGss"}";
var jsonBytes = Encoding.UTF8.GetBytes(json);
using (var www = new UnityWebRequest("https://mywebsite.com/profile/MyApp", "POST"))
{
www.uploadHandler = new UploadHandlerRaw(jsonBytes);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.SetRequestHeader("Accept", " text/plain");

yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
}
}

为了方便地配置它,例如通过Inspector或传递值,而不必手动编写JSON,您可以很容易地创建一个类,例如

[Serializable]
public class PostData
{
public Values values;
public bool consentAccepted;
public string consentToken;
}
[Serializable]
public class Values
{
public string AppName;
public string AppUser;
}

然后简单地进行例如

var jsonData = new PostData
{
values = new Values
{
AppName = "Test001",
AppUser = "Rein"
},
consentAccepted = true,
consentToken = "tz677zuiuis2qEZKo3Lt+kHluOGss"
}
var json = JsonUtility.ToJson(jsonData);
var jsonBytes = Encoding.UTF8.GetBytes(json);

除了代码中的JSON结构错误之外,用户derHugo的解决方案是正确的。我修复了它,这是完整的解决方案。

private string json = @"{
'values': {
'AppName': 'Test001',
'AppUser': 'Rein'
},
'consentAccepted': true,
'consentToken': 't65wRU6rttK1klzu768'
}";
var jsonBytes = Encoding.UTF8.GetBytes(json);
using (var www = new UnityWebRequest("https://mywebsite.com/profile/MyApp", "POST"))
{
www.uploadHandler = new UploadHandlerRaw(jsonBytes);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.SetRequestHeader("Accept", " text/plain");

yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
}
}

最新更新