Hello!
Below is a very simple REST class around the WWW object.
It sends a HTTP request, calls the callback when necessary and protects it in case of bad request.
The actual class is slightly more complicated
public delegate void RequestCallback (WWW request);
public delegate void DataCallback (string text);
public class REST : MonoBehaviour
{
public DataCallback MakeRequestCallback(APICallback callback)
{
return (request) =>
{
if( !string.IsNullOrEmpty( request.error ) )
{
Debug.LogError( "Error during request: " + request.error );
}
else if( c!=null )
{
callback(request.text);
}
};
}
public IEnumerator MakeRequest (string url, RequestCallback callback)
{
WWW request = new WWW(url);
return WaitForRequest(request, callback);
}
}
When I want to fetch data, I can do something like this (from inside a MonoBehaviour):
// REST rest is accessed on the Awake() of the MonoBehaviour
// doSomething could be print or Debug.LogError
string url = "http://mydomain.com/myscript.php";
RequestCallback callback = rest.MakeRequestCallback( doSomething );
StartCoroutine(rest.MakeRequest(url, callback));
Now all this works fine, unless the script on the server does something funky like a HTTP 302 redirection (which translates in PHP as header(âLocation: pathâ); )
Letâs say for example that I have static ASCII data files and a PHP script to pick one randomly. The most natural way would be to redirect to that random file.
If I do that, the following message appears in my console:
âError during request: unsupported urlâ
It could be the extension of the file that makes it an ugly URL. But I donât think so: I printed the âunsupportedâ URL in the console from the if-block of âError during requestâ and it was exactly the path to my PHP script.
I solved my problem by dumping the contents of the chosen file into the return of the script, but I feel itâs not as scalable as a redirection would have been. And not a good practice in general (some of the files can be lengthy).
I havenât tried to access the file directly from a WWW request yet, I will do and update this post, however I found no reference on âunsupported URLsâ or redirect headers with WWW, so I thought it would be good to share.
As I use iOS, I cannot use the other framework WebRequest/HTTPRequest.
Is it a bug? Is it the expected behavior?
Thanks,
Antho