C# 从Unity内部以JSON格式调用Uber API
我在Unity内部使用Uber API,我可以登录并进行身份验证以获取令牌,但在调用实际API时遇到了障碍 我相信我的问题是我需要以JSON格式进行调用,但我不知道如何做到这一点。一般来说,我对HTTP和API都是新手。这是我的密码:C# 从Unity内部以JSON格式调用Uber API,c#,json,unity3d,uber-api,C#,Json,Unity3d,Uber Api,我在Unity内部使用Uber API,我可以登录并进行身份验证以获取令牌,但在调用实际API时遇到了障碍 我相信我的问题是我需要以JSON格式进行调用,但我不知道如何做到这一点。一般来说,我对HTTP和API都是新手。这是我的密码: private IEnumerator TestRequest(){ Debug.Log(sToken); WWWForm form = new WWWForm(); //WWW www = new WWW(); form.
private IEnumerator TestRequest(){
Debug.Log(sToken);
WWWForm form = new WWWForm();
//WWW www = new WWW();
form.headers["Content-Type"] = "application.json";
form.headers["Authorization"] = "Bearer " +sToken;
form.AddField( "fare_id", "abcd");
form.AddField("product_id", "a1111c8c-c720-46c3-8534-2fcdd730040d");
form.AddField("start_latitude", "37.761492");
form.AddField("start_longitude", "-122.42394");
form.AddField("end_latitude", "37.775393");
form.AddField("end_longitude", "-122.417546");
yield return null;
using(UnityWebRequest uweb = UnityWebRequest.Post("https://sandbox-
api.uber.com/v1.2/requests", form)){
yield return uweb.Send();
if(uweb.isError) Debug.Log(uweb.error);
else Debug.Log(uweb.downloadHandler.text);
//GetVals(uweb.downloadHandler.text);
}
}
这在其他领域对我来说是可行的,但在这方面不行,我认为这与内容类型是JSON有关,但我不知道如何以正确的格式发送它。抱歉,我不能说得更具体些,我只是想了解一下这件事
任何帮助都将不胜感激 如果您将ContentType指定为application/json,我想您也应该以实际的json格式发送内容。我写了一个例子。这使用了Newtonsoft Json,但您应该对任何Json实现都很满意。此外,这或多或少是伪代码,您可能需要进行一些最终调整
using Newtonsoft.Json;
private IEnumerator TestRequest()
{
var jsonObject = new
{
fare_id = "abcd",
product_id = "a1111c8c-c720-46c3-8534-2fcdd730040d",
start_latitude = 37.761492f,
start_longitude = -122.42394f,
end_latitude = 37.775393f,
end_longitude = -122.417546f,
};
MemoryStream binaryJson = new MemoryStream();
using (StreamWriter writer = new StreamWriter(binaryJson))
new JsonSerializer().Serialize(writer, jsonObject);
using (UnityWebRequest uweb = UnityWebRequest.Post("https://sandbox-api.uber.com/v1.2/requests"))
{
uweb.SetRequestHeader("Authorization", "Bearer " + sToken);
uweb.SetRequestHeader("Content-Type", "application/json");
UploadHandlerRaw uploadHandler = new UploadHandlerRaw(binaryJson.ToArray());
uweb.uploadHandler = uploadHandler;
yield return uweb.Send();
if(uweb.isError)
Debug.Log(uweb.error);
else
Debug.Log(uweb.downloadHandler.text);
}
}
与前面提到的其他内容一样,
application.json
应该是application/json
这不是唯一的问题。因为它是json,所以不需要使用WWWForm
class。创建一个类来保存Json数据,然后创建它的新实例。将实例转换为json并将其传递给UnityWebRequest
Post函数的第二个参数
UnityWebRequest:
对于UnityWebRequest
,使用UnityWebRequest Post(字符串uri,字符串postData)代码>重载,用于传递url和json数据。然后使用SetRequestHeader
设置头
[Serializable]
public class UberJson
{
public string fare_id;
public string product_id;
public double start_latitude;
public double start_longitude;
public double end_latitude;
public double end_longitude;
}
void Start()
{
postJson();
}
string createUberJson()
{
UberJson uberJson = new UberJson();
uberJson.fare_id = "abcd";
uberJson.product_id = "a1111c8c-c720-46c3-8534-2fcdd730040d";
uberJson.start_latitude = 37.761492f;
uberJson.start_longitude = -122.42394f;
uberJson.end_latitude = 37.775393f;
uberJson.end_longitude = -122.417546f;
//Convert to Json
return JsonUtility.ToJson(uberJson);
}
void postJson()
{
string URL = "https://sandbox-api.uber.com/v1.2/requests";
//string json = "{ \"fare_id\": \"abcd\", \"product_id\": \"a1111c8c-c720-46c3-8534-2fcdd730040d\", \"start_latitude\": 37.761492, \"start_longitude\": -122.423941, \"end_latitude\": 37.775393, \"end_longitude\": -122.417546 }";
string json = createUberJson();
string sToken = "";
//Set the Headers
UnityWebRequest uwrq = UnityWebRequest.Post(URL, json);
uwrq.SetRequestHeader("Content-Type", "application/json");
uwrq.SetRequestHeader("Authorization", "Bearer " + sToken);
StartCoroutine(WaitForRequest(uwrq));
}
IEnumerator WaitForRequest(UnityWebRequest uwrq)
{
//Make the request
yield return uwrq.Send();
if (String.IsNullOrEmpty(null))
{
Debug.Log(uwrq.downloadHandler.text);
}
else
{
Debug.Log("Error while rececing: " + uwrq.error);
}
}
如果UnityWebRequest
不起作用,请使用WWW
。有报道称UnityWebRequest出现了bug,但我个人没有遇到过
WWW:
对于WWW
,使用公共WWW(字符串url,字节[]postData,字典标题)代码>构造函数重载,它在一个函数调用中接收url、数据和头
[Serializable]
public class UberJson
{
public string fare_id;
public string product_id;
public double start_latitude;
public double start_longitude;
public double end_latitude;
public double end_longitude;
}
void Start()
{
postJson();
}
string createUberJson()
{
UberJson uberJson = new UberJson();
uberJson.fare_id = "abcd";
uberJson.product_id = "a1111c8c-c720-46c3-8534-2fcdd730040d";
uberJson.start_latitude = 37.761492f;
uberJson.start_longitude = -122.42394f;
uberJson.end_latitude = 37.775393f;
uberJson.end_longitude = -122.417546f;
//Convert to Json
return JsonUtility.ToJson(uberJson);
}
void postJson()
{
string URL = "https://sandbox-api.uber.com/v1.2/requests";
//string json = "{ \"fare_id\": \"abcd\", \"product_id\": \"a1111c8c-c720-46c3-8534-2fcdd730040d\", \"start_latitude\": 37.761492, \"start_longitude\": -122.423941, \"end_latitude\": 37.775393, \"end_longitude\": -122.417546 }";
string json = createUberJson();
string sToken = "";
//Set the Headers
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
headers.Add("Authorization", "Bearer " + sToken);
//headers.Add("Content-Length", json.Length.ToString());
//Encode the JSON string into a bytes
byte[] postData = System.Text.Encoding.UTF8.GetBytes(json);
WWW www = new WWW(URL, postData, headers);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
if (String.IsNullOrEmpty(null))
{
Debug.Log(www.text);
}
else
{
Debug.Log("Error while rececing: " + www.error);
}
}
[可序列化]
公共类UberJson
{
公共字符串票价标识;
公共字符串产品标识;
公共双启动纬度;
公共双启动;
公共双端纬度;
公共双端经度;
}
void Start()
{
postJson();
}
字符串createUberJson()
{
UberJson UberJson=新的UberJson();
uberJson.fare_id=“abcd”;
uberJson.product_id=“a1111c8c-c720-46c3-8534-2fcdd730040d”;
uberJson.start_纬度=37.761492f;
uberJson.start_经度=-122.42394f;
uberJson.end_纬度=37.775393f;
uberJson.end_经度=-122.417546f;
//转换为Json
返回JsonUtility.ToJson(uberJson);
}
void postJson()
{
字符串URL=”https://sandbox-api.uber.com/v1.2/requests";
//字符串json=“{\”票价id\”:\“abcd\”,“产品id\”:\“a1111c8c-c720-46c3-8534-2fcdd730040d\”,“起点纬度”:37.761492,“起点经度”:122.423941,“终点纬度”:37.775393,“终点经度”:-122.417546};
字符串json=createUberJson();
字符串sToken=“”;
//设置标题
字典头=新字典();
添加(“内容类型”、“应用程序/json”);
标题。添加(“授权”、“持票人”+sToken);
//headers.Add(“Content-Length”,json.Length.ToString());
//将JSON字符串编码为字节
byte[]postData=System.Text.Encoding.UTF8.GetBytes(json);
WWW=新的WWW(URL、postData、标题);
启动例行程序(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW)
{
收益率;
if(String.IsNullOrEmpty(null))
{
Debug.Log(www.text);
}
其他的
{
Log(“接收时出错:+www.Error”);
}
}
我想知道您是否应该这样做:form.headers[“Content Type”]=“application/json”
(注意斜杠而不是点)还有,sToken
是服务器令牌吗?如果是,那么该行应该是:form.headers[“Authorization”]=“Token”+sToken代码>谢谢@Charlyn,但这并没有解决问题。我确实需要将它改为“application/json”,我还尝试了“Bearer”和“Token”,但都不起作用。我还尝试了从开发者仪表板生成的访问令牌,这让我相信问题在于我传递信息的格式。虽然不确定。我对JSON格式的思考是因为这样的帖子:,但我不知道如何使用Unity C#功能来复制相同的东西。感谢您花时间看这个@Thomas Hilbert,我已经尝试过了,但仍然无法实现。我在协程之外使用了一个结构来存储值,但是当我在BinaryJson MemoryStream上调用JsonSerializer时,它是0字节。因此使用了以下内容:字符串s=JsonUtility.ToJson(j);byte[]byteArray=System.Text.Encoding.UTF8.GetBytes(s);你知道这是否仍然有效吗?对不起,没有人!很抱歉我反应太晚了。我修复了这个示例,binaryJson现在正确地填充了数据JsonUtility
也可以,但是不能使用匿名类型,这就是为什么我在示例中更喜欢Newtonsoft.Json。非常感谢@Programmer!使用www确实有效!在使用UnityWebRequest时,身份验证似乎存在一些问题,这有点令人沮丧,但至少它可以工作!我真的很感谢你花时间帮我解决这个问题,这是最后一块拼图了!是的,这确实是一个带有UnityWebRequest
的bug。好东西WWW
是一个选项和解决方案。快乐编码!