【问题标题】:Get Unity WWW response status code获取 Unity WWW 响应状态码
【发布时间】:2015-10-22 02:40:58
【问题描述】:

我正在使用 Unity WWW 处理一些 Rest API 请求。但它不支持获取响应状态(只返回文本和错误)。有什么解决办法吗?谢谢!

【问题讨论】:

  • 供将来参考:如果您收到 301 重定向,然后出现错误消息,则 Unity 的响应标头将包含 301,而不是错误。 :(

标签: api rest http response


【解决方案1】:

编辑: 自从我提出这个问题后,Unity 发布了一个新的 HTTP 通信框架,称为 UnityWebRequest。它比 WWW 更现代,并提供对响应代码的明确访问,以及在标头、HTTP 动词等方面的更大灵活性。您可能应该使用它而不是 WWW。


显然你需要自己从响应头中解析它。

这似乎可以解决问题:

public static int getResponseCode(WWW request) {
  int ret = 0;
  if (request.responseHeaders == null) {
    Debug.LogError("no response headers.");
  }
  else {
    if (!request.responseHeaders.ContainsKey("STATUS")) {
      Debug.LogError("response headers has no STATUS.");
    }
    else {
      ret = parseResponseCode(request.responseHeaders["STATUS"]);
    }
  }

  return ret;
}

public static int parseResponseCode(string statusLine) {
  int ret = 0;

  string[] components = statusLine.Split(' ');
  if (components.Length < 3) {
    Debug.LogError("invalid response status: " + statusLine);
  }
  else {
    if (!int.TryParse(components[1], out ret)) {
      Debug.LogError("invalid response code: " + components[1]);
    }
  }

  return ret;
}

【讨论】:

    猜你喜欢
    • 2016-02-07
    • 2017-09-26
    • 2021-03-15
    • 1970-01-01
    • 2011-07-17
    • 2015-07-23
    • 2015-05-28
    • 2020-01-10
    • 2015-05-21
    相关资源
    最近更新 更多