Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Unity WWW response status code

I'm working with Unity WWW for some Rest API request. But it don't support to get response status (only return text and error). Any solution for it? Thanks!

like image 879
minh thinh Avatar asked Oct 22 '15 02:10

minh thinh


1 Answers

edit: Since the time I asked this question, Unity released a new framework for HTTP communications called UnityWebRequest. It's much more modern than WWW, and provides definitive access to the Response Code, as well as more flexibility around headers, HTTP verbs, etc. You should probably use that instead of WWW.


apparently you need to parse it from the response headers yourself.

this seems to do the trick:

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;
}
like image 124
orion elenzil Avatar answered Oct 18 '22 00:10

orion elenzil