获取Unity WWW响应状态代码

时间:2015-10-22 02:40:59

标签: api rest http response

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

1 个答案:

答案 0 :(得分:12)

编辑:自从我提出这个问题以来,Unity发布了一个名为UnityWebRequest的HTTP通信新框架。它比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;
}