从 Unity 中以 JSON 格式调用 Uber API

Make call to Uber API in JSON format from within Unity

我在 Unity 中使用 Uber API,我可以登录然后进行身份验证以获取令牌,但是在调用实际 [=21] 时我 运行 遇到了障碍=].

我认为我的问题是我需要以 JSON 格式进行调用,但我不知道该怎么做。一般来说,我是 HTTP 和 API 的新手。这是我的代码:

    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。创建一个 class 来保存 Json 数据,然后创建它的新实例。将实例转换为 json 并将其传递给 UnityWebRequest Post 函数的第二个参数。

UnityWebRequest:

对于 UnityWebRequest,使用 UnityWebRequest Post(string uri, string postData); 重载,让您传递 url 和 json 数据。然后使用 SetRequestHeader 设置 headers。

[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 错误的报告,但我个人没有遇到过。

WWW:

对于 WWW,使用 public WWW(string url, byte[] postData, Dictionary<string, string> headers); 构造函数重载,它在一个函数调用中接收 url、数据和 headers。

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