我正在使用unity www来处理一些rest api请求。但它不支持获取响应状态(仅返回文本和错误)。有什么解决办法吗?谢谢!

最佳答案

编辑:自从我提出这个问题以来,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;
}

08-03 16:33
查看更多