简体   繁体   English

从统一C#将json字符串发布到webAPI; HttpClient还是UnityWebRequest?

[英]POST json string to webAPI from unity C#; HttpClient or UnityWebRequest?

I am trying to POST a json string to a web API and currently got this code: 我正在尝试将json字符串发布到Web API,并且当前得到以下代码:

async Task<Uri> Post(CapturedImage image)
{
    string json = JsonConvert.SerializeObject(image);
    var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync(url, content);
    response.EnsureSuccessStatusCode();
    Debug.Log("Request Message Information:- \n\n" + response.RequestMessage + "\n");

    Debug.Log(json.ToString());

    // return URI of the created resource.
    return response.Headers.Location;
}

The code is not done yet so I'm not sure this is the type I want to return in the end (in the end I will have a new json string with information about a specific car supposedly). 代码还没有完成,所以我不确定这到底是我要返回的类型(最后,我会有一个新的json字符串,其中包含有关特定汽车的信息)。

Unity hangs when it comes to the line HttpResponseMessage response = await client.PostAsync(url, content); HttpResponseMessage response = await client.PostAsync(url, content); Unity挂起HttpResponseMessage response = await client.PostAsync(url, content); and I have to forcefully close the unity app. 并且我必须强制关闭统一应用程序。

How can I use the httpClient successfully? 如何成功使用httpClient I am not using the unityWebRequest for the moment because I don't understand in which way WWWForm is being sent (like an object I guess). 我暂时不使用unityWebRequest ,因为我不知道以哪种方式发送WWWForm (我猜像是一个对象)。 And I don't want a byte[] to be sent either, but a json string and I can assume that the WWWForm is like a json string but separated-ish. 而且我也不希望发送byte [],而是要发送json字符串,并且我可以假定WWWForm类似于json字符串,但分离。 Also I don't get which type to be received in the web API either when its a WWWForm . 另外,当它是WWWForm时,我也不会在Web API中接收哪种类型。 Like if its a json string I just have the parameter like (string json) . 就像如果它是一个json字符串,我只是具有(string json)这样的参数。

Am I thinking completely wrong with not using unityWebRequest instead of httpClient ? 我是否认为不使用unityWebRequest而不是httpClient完全错误? I have to use json if possible. 如果可能,我必须使用json。

UnityWebRequest.Post(string URL, string data) also takes string as data input not only a WWWForm . UnityWebRequest.Post(string URL, string data)不仅将WWWForm作为string ,还将string作为数据输入。

Usually you would use it in a Coroutine 通常你会在协程中使用它

In order to get a result back you could add a simple callback 为了获得结果,您可以添加一个简单的回调

IEnumerator Upload(string URL, string jsonData, Action<string> callback)
{
    using (UnityWebRequest www = UnityWebRequest.Post(URL, jsonData))
    {
        www.SetRequestHeader("Content-Type", "application/json");

        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
            callback?.Invoke(www.GetResponseHeader("Location"));
        }
    }
}

and use it with 并与

StartCoroutine(Upload(someURL, someJsonData, 
    // e.g. as lambda expression
    result => 
    {
        Debug.Log(result);
    }
));

or with a method 或用一种方法

StartCoroutine(Upload(someURL, someJsonData, HandleUploadResult);

...

private void HandleUploadResult(string result)
{
    Debug.Log(result);
}

But if you really need it to be used with await as said this looks promising (though neevr tried it): 但是,如果您确实需要将其与await一起使用,那么看起来很有希望(尽管neevr尝试过):

public class UnityWebRequestAwaiter : INotifyCompletion
{
    private UnityWebRequestAsyncOperation asyncOp;
    private Action continuation;

    public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation asyncOp)
    {
        this.asyncOp = asyncOp;
        asyncOp.completed += OnRequestCompleted;
    }

    public bool IsCompleted { get { return asyncOp.isDone; } }

    public void GetResult() { }

    public void OnCompleted(Action continuation)
    {
        this.continuation = continuation;
    }

    private void OnRequestCompleted(AsyncOperation obj)
    {
        continuation();
    }
}

public static class ExtensionMethods
{
    public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp)
    {
        return new UnityWebRequestAwaiter(asyncOp);
    }
}

It looks complicated but ... you don't have to do anything with it just put it somewhere in your Assets . 它看起来很复杂,但是...您不必做任何事情,只要将它放在您的Assets

Then as far as I understand it you can simply use something like 据我了解,您可以简单地使用

www = UnityWebRequest.Post(URL, jsonData);
www.SetRequestHeader("Content-Type", "application/json");
await www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
    Debug.Log(www.error);
}
else
{
    Debug.Log("Form upload complete!");
    var result = www.GetResponseHeader("Location");
}

There are other sources which do something similar .. maybe better? 还有其他来源做类似的事情..也许更好?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM