向 Vuforia 的 Web 服务发出 POST 请求总是导致 "Fail",即使 PUT 请求总是使用相同的 approach/body

Making POST request to Vuforia's Web Services always results in "Fail", even though PUT request always works using same approach/body

我正在 Unity 中开发 Android 应用程序。我正在尝试让 UnityWebRequests 与 Vuforia 的 Web 服务一起工作 API。目前每种方法都有效 - GET/PUT/DELETE,但我不能 POST 任何东西,我总是收到错误消息:

Error:Generic/unknown HTTP error
Response code:400

尽管根据 Vuforia 的 documentation POST 需要与 PUT 相同的请求主体,并且我使用相同的方法生成它:

public string CreateNewUpdateBody(Text name, Text width, RawImage image, Toggle active_flag, Text application_metadata)
{
    dynamic BodyData = new System.Dynamic.ExpandoObject();

    if (!string.IsNullOrEmpty(name.text))
    {
        BodyData.name = name.text; // mandatory for post
    }
    if (!string.IsNullOrEmpty(width.text))
    {
        BodyData.width = float.Parse(width.text); // mandatory for post
    }
    if (image.texture != null)
    {
        Texture2D texture = (Texture2D)image.texture;
        BodyData.image = System.Convert.ToBase64String(ImageConversion.EncodeToJPG(texture)); // mandatory for post
    }
    if (active_flag.interactable)
    {
        BodyData.active_flag = active_flag.isOn;
    }
    if (!string.IsNullOrEmpty(application_metadata.text))
    {
        BodyData.application_metadata = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(application_metadata.text));
    }
    string json = JsonConvert.SerializeObject(BodyData);

    Debug.Log("Body data: " + json);

    return json;
}

然后我像这样发送网络请求:

private IEnumerator PostTarget(MonoBehaviour mono, string postBody)
{
    var request = UnityWebRequest.Post(url + "/targets", postBody);

    SetHeaders(request); // Must be done after setting the body

    Debug.Log("Starting request " + request.method + " " + request.url);

    yield return request.SendWebRequest();

    while (!request.isDone) yield return null;

    if (request.isHttpError || request.isNetworkError)
    {
        Debug.LogError("Request was not completed");
        Debug.LogError("Error:" + request.error + " Response code:" + request.responseCode);
        Debug.LogError(request.downloadHandler.text); // result_code is always just "Fail"
        mono.StopAllCoroutines();
        yield break;
    }
    else
    {
        Debug.Log("Request completed successfuly!");
        Debug.Log(request.downloadHandler.text);
    }

    response = JsonUtility.FromJson<ResponsePostNewTarget>(request.downloadHandler.text);

    Debug.Log("\nCreated target with id: " + response.target_id);
}

有什么想法或建议吗?感谢您花时间阅读本文。

如果一切正常但发布数据,要么 1 vuforia 不支持它,要么 2(很可能)你遗漏了一些东西。

尝试将此添加到您的请求中

private UploadHandler GetUploadHandler(string postBody)
{
    UploadHandler handler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(postBody));
    handler.contentType = "application/json";
    return handler;
}

并在SetHeaders后调用

request.uploadHandler = GetUploadHandler(postBody);