0

I want to call a WebClient like this:

using (TimeoutWebClient client = new TimeoutWebClient())
            {
                System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
                reqparm.Add("email", email);
                reqparm.Add("pass", password);
                Debug.Log("5");

                if (!string.IsNullOrEmpty(arg))
                        reqparm.Add(arg, "please");

                Uri url = new Uri(URL);
                byte[] responsebytes = client.UploadValues(url, "POST", reqparm);
                Debug.Log("6");
                string responsebody = Encoding.UTF8.GetString(responsebytes);
                // Debug here
                return responsebody;
            }
        }
        catch (TimeoutException)
        {
            Debug.LogWarning("Timeout while request, retry !");
            Debug.Log("7");
        }
        catch (Exception e)
        {
            Debug.LogError("Exception while request: " + e.Message + e.StackTrace);
            return "Error";
        }

but when I run this, sometimes it make a a weird exception which goes like this:

Exception while request: An error occurred performing a WebClient request.  at System.Net.WebClient.UploadValues (System.Uri address, System.String method, System.Collections.Specialized.NameValueCollection data) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.Net.WebClient:UploadValues (System.Uri,string,System.Collections.Specialized.NameValueCollection)

and I don't really know what it mean so if someone already encounter a such strange exception, tell me :X . (I'm making a video game and that's the login post request)

PS: Under Unity and .NET 2.0 but it's almost the same ^^

EDIT: Here is the full log:

Message =  The request timed out   Help link =    Source = System   StackTrace =   at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 at System.Net.HttpWebRequest.GetResponse () [0x00000] in <filename unknown>:0 

EDIT: And here is the TimeoutWebClient class:

    public class TimeoutWebClient : WebClient
    {
    private int _timeOut = 7000; // 7s
    public int TimeOut
    {
        get
        {
            return _timeOut;
        }
        set
        {
            _timeOut = value;
        }
    }
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest webRequest = base.GetWebRequest(address);
        webRequest.Timeout = _timeOut;
        if (webRequest is HttpWebRequest)
        {
            (webRequest as HttpWebRequest).KeepAlive = false;
            (webRequest as HttpWebRequest).Timeout = _timeOut; //(tried different values)
        }
        return webRequest;
    }
}
Samuel Prevost
  • 1,047
  • 1
  • 11
  • 30

3 Answers3

0

It means your request is taking longer than 7 seconds to connect. Either the URL you are connecting to is incorrect or there is a issue with the server.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • I know that Sherlocks ! The problem is that a strange timeout happens and I don't see where ! – Samuel Prevost Mar 03 '16 at 16:01
  • The error happens on `byte[] responsebytes = client.UploadValues(url, "POST", reqparm);` the value of `url` is the problem. Either the URL is wrong or the server that exists at that url is non-functioning. I would reccomend using the debugger and putting a breakpoint in at that line and see what the value of `url` is, perhaps it is not the value you are expecting it to be. Are you using Visual Studio or Mono Develop as the C# editor with Unity? The instructions for debugging is different for each. – Scott Chamberlain Mar 03 '16 at 16:08
  • I know it work, I host it on http://ovh.com/ , I wrote this script myself and I checked it manually, it work well. And the problem isn't there, because half time, it work so the problem come from timeout. I define the url manually upward in the code so I know the url format isn't the problem – Samuel Prevost Mar 03 '16 at 16:11
0

Ok, finally, I decided to use the WWW class from Unity API instead of .NET API because it seems to be optimised. If you want to know the code I'm using, here it is:

    WWWForm form = new WWWForm();
    form.AddField("email", email);
    form.AddField("pass", password);

    if (!string.IsNullOrEmpty(arg))
        form.AddField(arg, "please");

    WWW www = new WWW(URL, form);
    // Wait until the request has been sent
    yield return www;

    if (www.isDone)
    {
        Debug.Log("WWW text = " + www.text);
        if (callback(www.text))
        {
            // we are logged
        }
        else
        {
            // we arn't
        }
    }
Samuel Prevost
  • 1,047
  • 1
  • 11
  • 30
-1

Why you're not using HttpClient instead, here is a simple code of Get/Post request using httpClient and Json.net

     public async Task<T> MakeHttpClientRequestASync<T>(string requestUrl, string authenticationToken,
        Dictionary<string, string> requestContent, HttpMethod verb, Action<Exception> error)
    {
        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue() { NoCache = true };
        HttpResponseMessage response;

        var returnVal = default(T);

        try
        {
            if (verb == HttpMethod.Post)
            {
                response = await httpClient.PostAsync(requestUrl, new FormUrlEncodedContent(requestContent));
            }
            else
            {
                response = await httpClient.GetAsync(requestUrl);
            }

            var resultString = await response.Content.ReadAsStringAsync();
            returnVal = JsonConvert.DeserializeObject<T>(resultString);
        }
        catch (Exception ex)
        {
            error(ex);
        }

        return returnVal;
    }
esiprogrammer
  • 1,438
  • 1
  • 17
  • 22
  • Thanks for your answer @esiprogrammer but as I wrote one the initial question: ---> " PS: Under .NET 2.0 but it's almost the same ^^ " <--- and System.Net.Http don't exist in .NET 2.0 and I can't upgrade (compatibility etc, I can't decide) – Samuel Prevost Mar 03 '16 at 16:03