使用发布请求在Unity中返回多个值

时间:2018-08-02 10:37:57

标签: unity3d

我是Unity新手,我从中创建了一个Post请求,我想返回Authentication-Token标头和授权标头,其中一些必需的json数据是我的代码

private IEnumerator BasketId()
{
    string url = "http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-inTRONICS-Site/-/baskets/";
    using (UnityWebRequest request = UnityWebRequest.Post(url, "Hello"))
    {
        yield return request.SendWebRequest();
        string token = request.GetResponseHeader("Authentication-token");
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            string jsonResut = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
            obj = JsonConvert.DeserializeObject<BasketId>(jsonResut);
            Debug.Log(obj.Uri);
            Debug.Log("Authentication-Token: " + token);            
            yield return obj.Title;
            yield return token;
        }
    }
}

所以我可以返回值。请帮助我。

1 个答案:

答案 0 :(得分:1)

因为协程不是立即(阻止)的,所以您将无法直接返回响应。您需要做的是拥有一个事件或回调,当您的请求完成时将被调用。

这是通过将回调作为参数传递来实现的方法:

private IEnumerator GetBasketId(System.Action<string, BasketId> callback)
{
    string url = "http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-inTRONICS-Site/-/baskets/";
    using (UnityWebRequest request = UnityWebRequest.Post(url, "Hello"))
    {
       yield return request.SendWebRequest();
       if (request.isNetworkError || request.isHttpError)
       {
          Debug.Log(request.error);
          if (callback != null)
          {
             callback(null, null);
          }
          // callback?.Invoke(null, null); // for short
          }
          else
          {
             if (callback != null)
             {
                string token = request.GetResponseHeader("Authentication-token");
                string jsonResut = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
                obj = JsonConvert.DeserializeObject<BasketId>(jsonResut);
                if (callback != null)
                {
                   callback(token, obj);
                }
                // callback?.Invoke(token, obj); // for short
             }
          }
     }
}

因此,当您要启动请求时,只需调用以下内容:

StartCoroutine(GetBasketId((token, basketId) =>
{
   if (string.IsNullOrEmpty(token))
   {
      // Handle error
   }
   else
   {
      // Handle success
      Debug.Log("Token: " + token);
      Debug.Log(basketId.Title);
   }
});