Search Unity

Best HTTP Released

Discussion in 'Assets and Asset Store' started by BestHTTP, Sep 11, 2013.

  1. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    188
    I am posting this as an alternative solution to help anyone facing the same problem in the future.

    I was getting an error in the HTTPUrlEncodedForm.GetData() operation, because the Uri.EscapeDataString() has a limit that was generating the following error:
    I think this error happened because I have changed the HTTPFormBase.LongLength from 256 to int.MaxValue, because the server I need send request does not accept Content-Type as binary type.

    To fix this error, I created an Extension Method:
    Code (CSharp):
    1. public static string EscapeString(this string originalString)
    2. {
    3.     int limit = 2000;
    4.  
    5.     StringBuilder sb = new StringBuilder();
    6.     int loops = originalString.Length / limit;
    7.  
    8.     for (int i = 0; i <= loops; i++)
    9.     {
    10.         if (i < loops)
    11.         {
    12.             sb.Append(Uri.EscapeDataString(originalString.Substring(limit * i, limit)));
    13.         }
    14.         else
    15.         {
    16.             sb.Append(Uri.EscapeDataString(originalString.Substring(limit * i)));
    17.         }
    18.     }
    19.     return sb.ToString();
    20. }
    I have changed the lines with "Uri.EscapeDataString" to use my extension method, like this:
    Code (CSharp):
    1. for (int i = 0; i < Fields.Count; ++i)
    2. {
    3.     var field = Fields[i];
    4.  
    5.     if (i > 0)
    6.         sb.Append("&");
    7.  
    8.     //sb.Append(Uri.EscapeDataString(field.Name));
    9.     sb.Append(field.Name.EscapeString());
    10.     sb.Append("=");
    11.  
    12.     if (!string.IsNullOrEmpty(field.Text) || field.Binary == null)
    13.         //sb.Append(Uri.EscapeDataString(field.Text));
    14.         sb.Append(field.Text.EscapeString());
    15.     else
    16.         // If forced to this form type with binary data, we will create a string from the binary data first and encode this string.
    17.         //sb.Append(Uri.EscapeDataString(Encoding.UTF8.GetString(field.Binary, 0, field.Binary.Length)));
    18.         sb.Append(Encoding.UTF8.GetString(field.Binary, 0, field.Binary.Length).EscapeString());
    19. }
     
  2. Dynamoid-Megan

    Dynamoid-Megan

    Joined:
    Apr 16, 2015
    Posts:
    72
    Hello there, I am wondering when we might be able to get our hands on the BestHTTP Pro update with WebGL support, which I'm sure a lot of people are really excited about! I saw the post that it was uploaded to the Asset Store on October 10th, how long does it usually take to update after submitting?
     
  3. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    188
    I am posting another solution I did in order to manage my download and abort the request when a determined time has passed without receive fragments.

    Code (CSharp):
    1. public static void DownloadFile(string url, string directoryToSave, UILabel progressLabel, Action<string, string> successCallback, Action errorCallback)
    2. {
    3.     bool needCheckTimeout = true;
    4.     Thread timeoutThread = null;
    5.     long fileLength = 0;
    6.  
    7.     string fileName = url.Substring(url.LastIndexOf("/") + 1);
    8.     string filePath = directoryToSave + @"/" + fileName;
    9.  
    10.     if (File.Exists(filePath))
    11.         File.Delete(filePath);
    12.  
    13.     var request = new HTTPRequest(new Uri(url), (req, resp) =>
    14.     {
    15.         if (resp == null)
    16.         {
    17.             needCheckTimeout = false;
    18.             if (timeoutThread != null && timeoutThread.IsAlive)
    19.             {
    20.                 timeoutThread.Abort();
    21.             }
    22.  
    23.             Debug.LogError(string.Format("Utilities.DownloadFile - Failed! Arquivo: {0}", fileName));
    24.             errorCallback();
    25.             return;
    26.         }
    27.  
    28.         List<byte[]> fragments = resp.GetStreamedFragments();
    29.  
    30.         if (fragments != null)
    31.         {
    32.             // Write out the downloaded data to a file:
    33.             using (FileStream fs = new FileStream(filePath, FileMode.Append))
    34.             {
    35.                 foreach (byte[] data in fragments)
    36.                 {
    37.                     fs.Write(data, 0, data.Length);
    38.                     fileLength = fs.Length;
    39.                 }
    40.             }
    41.         }
    42.  
    43.         if (resp.IsStreamingFinished)
    44.         {
    45.             needCheckTimeout = false;
    46.             if (timeoutThread != null && timeoutThread.IsAlive)
    47.             {
    48.                 timeoutThread.Abort();
    49.             }
    50.  
    51.             Debug.Log(string.Format("Utilities.DownloadFile - Finished! Arquivo: {0}", fileName));
    52.             successCallback(directoryToSave, fileName);
    53.         }
    54.     });
    55.  
    56.     request.OnProgress += (HTTPRequest req, int downloaded, int length) =>
    57.     {
    58.         float progressPercent = (downloaded / (float)length) * 100.0f;
    59.         //Debug.Log("Downloaded: " + progressPercent.ToString("F2") + "%");
    60.         progressLabel.text = progressPercent.ToString("F0") + "%";
    61.     };
    62.  
    63.     request.UseStreaming = true; // Save to file
    64.     request.StreamFragmentSize = 1 * 1024 * 1024;
    65.     request.DisableCache = true; // already saving to a file, so turn off caching
    66.     request.IsCookiesEnabled = false;
    67.  
    68.     request.Send();
    69.  
    70.     // Thread to know if we need to generate the Timeout.
    71.     if (needCheckTimeout)
    72.     {
    73.         timeoutThread = new Thread(() =>
    74.         {
    75.             bool canAbort = false;
    76.             while (!canAbort)
    77.             {
    78.                 long lastFileLength = fileLength;
    79.                 Thread.Sleep(TimeSpan.FromSeconds(Configs.TIMEOUT_LIMIT));
    80.  
    81.                 // If it doesnt received more fragments after the Sleep, we are going to abort the request.
    82.                 if (fileLength <= lastFileLength)
    83.                 {
    84.                     canAbort = true;
    85.                 }
    86.             }
    87.  
    88.             Debug.LogWarning(string.Format("DownloadFile.Thread -> TimedOut. (url => {0})", url));
    89.             request.Abort();
    90.         });
    91.  
    92.         timeoutThread.Start();
    93.     }
    94. }
     
  4. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Dynamoid Megan That version contained a regression so I had to recall it from the Asset Store. A new version is uploaded on Oct 16, and it should be relesed on this week.
     
    slumtrimpet likes this.
  5. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    188
    @BestHTTP What is the better way to me know if:
    1. The device internet connection is online?
    2. The server I need send POST is available?

    When the request returns error, I need to print a message to my users know if the internet is offline or if the server is offline.
     
  6. oddurmagg

    oddurmagg

    Joined:
    Mar 20, 2013
    Posts:
    18
    Any news on SNI support ?

    I am using BestHTTP to talk to a REST backend which is fronted by AWS cloudfront, which uses SNI for SSL termination. With IOS 9 this becomes more of an issue, since to be strictly compatible, all app network traffic should be encrypted.

    Also, is there a way to make client side certificate pinning, that is, I want to say that api.mygame.com should always be encrypted with a cert with a specific hash/public key ?

    - Oddur
     
  7. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @sandolkakos The plugin doesn't distinguish between errors, i would recommend a plugin that is made for checking for the online connection. Or you can try to dig the exception in the request.Exception property, but the returned exception can be easily different for different platforms.
     
    sandolkakos likes this.
  8. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @oddurmagg SNI supported out of the box, when you switch to the alternate SSL handler. You can do it per-request(request.UseAlternateSSL = true;) or globally (HTTPManager.UseAlternateSSLDefaultValue = true;).

    Certificate pinning: I think it's possible with a custom CertificateVerifyer, but I don't have a working example. It's out of my knowlage, sorry.
     
  9. oddurmagg

    oddurmagg

    Joined:
    Mar 20, 2013
    Posts:
    18
    @BestHTTP: Are there any things to be aware when using the bouncycastle crypto ?
     
  10. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @oddurmagg I don't know nothing that you should aware of. I built the plugin so, that you should switch between the legacy and the bouncy castle implementation with just a switch.
     
  11. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    v1.9.3 and v1.9.4 are released today in the Asset Store.

    WebGL build support is here!
    There are disabled features for this build, but the plugin still remained rather feature rich. Also, all high level protocols supported: WebSockets, Socket.IO, SignalR, Server-Sent Events with their easy to use APIs!

    While i tried to make it bug free, this new platform required a lot of code changes. New bugs may be introduced, and may contain bugs specific to this new platform too.
    Please report them, and i will fix them as soon as i just can. As usually. :)

    Release notes of these updates:
    1.9.4 (2015.10.15)
    General
    -[Bugfix] Fixed a possible connection error on editors running on non-windows
    -[Improvement] Added two more constructors to the Cookie class

    1.9.3 (2015.10.10)
    -WebGL support added! Check out the documentation about the limitations.
    General
    -[Improvement] Improved shutdown handling in the editor
    -[Improvement] Cache will work on redirect uris as expected
    -[Bugfix] Tcp channel disconnection is now detected much quicker
    SignalR
    -[Improvement] Added support for SignalR 2.0.x
    -[Improvement] Improved logging in some cases
    WebSocket
    -[Bugfix] The plugin will detect a lost connection sooner


    CC: @Dynamoid Megan
     
    sandolkakos and slumtrimpet like this.
  12. Dynamoid-Megan

    Dynamoid-Megan

    Joined:
    Apr 16, 2015
    Posts:
    72
    @BestHTTP Thank you for the heads up! I have edited all my #if !UNITY_WEBGL code so that BestHTTP is included in my WebGL builds now. When I try to subscribe to a Websocket using WebGL build I get pthread error:
    missing function: pthread_create index.html:43:7
    Module.printErr() index.html:43
    _pthread_create() DBio3_WebGLBestHTTP2.js:1
    lF() DBio3_WebGLBestHTTP2.js:35
    uD() DBio3_WebGLBestHTTP2.js:35
    mbq() DBio3_WebGLBestHTTP2.js:44
    invoke_iiii() DBio3_WebGLBestHTTP2.js:1
    gB() DBio3_WebGLBestHTTP2.js:35
    Baq() DBio3_WebGLBestHTTP2.js:44
    etc... and
    Invoking error handler due to
    uncaught exception: abort(-1) at jsStackTrace@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:1:21731
    stackTrace@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:1:21914
    abort@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:51:53019
    _pthread_create@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:1:200349
    lF@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:35:288482
    uD@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:35:265454
    mbq@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:44:570046
    invoke_iiii@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:1:362806
    gB@file:///Users/mPerry/WebGLTests/DBio3_WebGLBestHTTP2/Release/DBio3_WebGLBestHTTP2.js:35:212272
    Baq@file:///Users/[…]

    The function I am trying to call looks like this with "serverURL" and "authToken" being manually set on Start in the scripts they are referenced in.
    Code (CSharp):
    1.     public void subscribeNow()
    2.     {
    3.         string address = "ws://"+ serverURL + ":9999/data/526/iw4be5j0/websocket";
    4.         webSocket = new WebSocket(new Uri(address));
    5.         authToken = NetworkingController.Instance.authToken;
    6.      
    7.         if (HTTPManager.Proxy != null)
    8.         {
    9.             webSocket.InternalRequest.Proxy = new HTTPProxy (HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
    10.         }
    11.         webSocket.OnOpen += OnOpen;
    12.         webSocket.OnMessage += OnMessageReceived;
    13.         webSocket.OnClosed += OnClosed;
    14.         webSocket.OnError += OnError;
    15.      
    16.         webSocket.Open();  
    17.     }
    I also wanted to mention this works fine in the editor still with websockets, just not when I load into Firefox as a WebGL build.
     
  13. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Dynamoid Megan That code shouldn't even compile. In WebGL builds InternalRequest is excluded. I forgot to exlude Proxy settings too, it will have no effect neither.
     
  14. slumtrimpet

    slumtrimpet

    Joined:
    Mar 18, 2014
    Posts:
    347
    Excellent work man. In less than 8 hours we've added WebGL support to our already mature product and are pushing it into the wild as we speak. Really appreciate you adding that feature.
     
    BestHTTP likes this.
  15. kalama

    kalama

    Joined:
    Oct 22, 2015
    Posts:
    1
    Do you support client side SSL certificates?
    Thanks,
    Eddie
     
  16. Dynamoid-Megan

    Dynamoid-Megan

    Joined:
    Apr 16, 2015
    Posts:
    72
    I seem to be having trouble with what seems like it should be straightforward implementation. Is there a working code snippet example I can look at, of subscribing to a Websocket using WebGL?
    I tried using the example SampleSelector scene in WebGL and got the same Pthread error. I am trying to run this code from the sample:
    Code (CSharp):
    1. if (webSocket == null && GUILayout.Button("Open Web Socket"))
    2.                 {
    3.                     // Create the WebSocket instance
    4.                     webSocket = new WebSocket(new Uri(address));
    5.  
    6.                     // Subscribe to the WS events
    7.                     webSocket.OnOpen += OnOpen;
    8.                     webSocket.OnMessage += OnMessageReceived;
    9.                     webSocket.OnClosed += OnClosed;
    10.                     webSocket.OnError += OnError;
    11.  
    12.                     // Start connecting to the server
    13.                     webSocket.Open();
    14.  
    15.                     Text += "Opening Web Socket...\n";
    16.                 }
     
    Last edited: Oct 23, 2015
  17. crushforth

    crushforth

    Joined:
    Jul 22, 2010
    Posts:
    113
    Does BestHTTP support SSL certificate validation on iOS & Android? I'm currently using UniWeb and attempting to validate the certificate like so:

    Code (csharp):
    1.  
    2. static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
    3.     Debug.Log("sslPolicyErrors:"+sslPolicyErrors);
    4.  
    5.     if (sslPolicyErrors == SslPolicyErrors.None)
    6.         return true;
    7.  
    8.     return false;
    9. }
    10.  
    I'm getting the following policy errors back (combined flags)
    sslPolicyErrors:RemoteCertificateNotAvailable, RemoteCertificateChainErrors

    All the other data seems to be filled in correctly so it is obtaining some sort of correct certificate information.

    The certificate on the server is fine and its not something I'd be able to modify as we don't have access to it. Just wondering if anyone knows how I can validate the certificate or if BestHTTP supports https certificate validation. I'll buy it right now if it does :)
     
  18. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @kalama I pretty sure Bouncy Castle (the code behind when request.UseAlternateSSL is set to true) can do it, however I didn't tried it, so there are no examples or easy way to do it.
     
  19. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Dynamoid Megan Can you try to create a new project, importing my plugin then build the samples for WebGL? I tried multiple machines and browsers and it's worked fine.
    Also, please make sure you are using the latest plugin.
     
  20. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @crushforth The default .NET implementation of the ssl handler is a little outdated in the mono version that Unity uses. My plugin bundled with an alternate handler. You can implement the ICertificateVerifyer interface and set it to a request:
    Code (CSharp):
    1. using System;
    2. using Org.BouncyCastle.Crypto.Tls;
    3. using Org.BouncyCastle.Asn1.X509;
    4.  
    5. class CustomVerifier : ICertificateVerifyer
    6. {
    7.     public bool IsValid(Uri serverUri, X509CertificateStructure[] certs)
    8.     {
    9.        // TODO: Return false, if validation fails
    10.            return true;
    11.     }
    12. }
    13.  
    14. var request = new HTTPRequest(new Uri("https://google.com"), ...);
    15. request.CustomCertificateVerifyer = new CustomVerifier();
    16. request.UseAlternateSSL = true;
    17. request.Send();
    Unfortunately however i can't help what should be in the IsValid function.
     
  21. Dynamoid-Megan

    Dynamoid-Megan

    Joined:
    Apr 16, 2015
    Posts:
    72
    It works!! Thank you so much, I have Websockets and Socket.IO working in Unity 5.2.2f1 after uploading to an FTP server.
     
  22. AwDogsGo2Heaven

    AwDogsGo2Heaven

    Joined:
    Jan 17, 2014
    Posts:
    102
    Hi I'm having trouble connecting to a Socket IO Server in my local network. I get this error:

    Err [HandshakeData]: Handshake request failed with error: Handshake request finished Successfully, but the server sent an error. Status Code: 404-Not Found Message: Cannot GET /io?EIO=4&amp;transport=polling&amp;t=2649596542-1&amp;b64=true
    Uri: http://192.XXX.X.XXX:9000/io?EIO=4&transport=polling&t=2649596542-1&b64=true

    Any idea on what the issue could be? I'm running this from the editor. Unity 5.2.

    edit: to clarify, I am able to connect using a javascript library to my server.
     
  23. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @AwDogsGo2Heaven The default path for Socket.IO urls are starts with /socket.io/, if you didn't changed it on the server you should connect like this:
    Code (CSharp):
    1. new SocketManager(new Uri("http://192.XXX.X.XXX:9000/socket.io/"), options);
    2.  
     
  24. AwDogsGo2Heaven

    AwDogsGo2Heaven

    Joined:
    Jan 17, 2014
    Posts:
    102
    edit:

    NVM, I'm using jwt token, and figured out I need to pass it using the AdditonalQueryParams.
     
  25. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @AwDogsGo2Heaven As noted in the AdditonalQueryParams' help, you have to escape(WWW.EscapeURL or Uri.EscapeDataString) the keys and values you add to this dictionary.
     
  26. RyuMaster

    RyuMaster

    Joined:
    Sep 13, 2010
    Posts:
    468
    Hi! I wonder, is it possible to get Stream with BEST HTTP? I have this code:

    Code (csharp):
    1.  
    2. HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
    3. response.GetResponseStream();
    4. Stream streamResponse = response.GetResponseStream();
    5. StreamReader streamRead = new StreamReader(streamResponse);
    6. ... new StreamReader(streamResponse).ReadToEnd()); ....
    7.  
    But inside BEST HTTP response class, I could not find any equivalent to 'GetResponseStream' to get access to response stream. Is there any way to do so?
     
  27. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @RyuMaster While it's not wrapped in a Stream, you have access to the downloaded bytes while it's still downloading. There is a working example in the \Assets\Best HTTP (Pro)\Examples\HTTP\LargeFileDownloadSample.cs.
     
  28. Tristan.fgol

    Tristan.fgol

    Joined:
    Sep 3, 2014
    Posts:
    12
    @BestHTTP after upgrading to 1.9.4 from 1.9.2 we are seeing an issue on Android only. The
    OnRequestFinishedDelegate of a HTTPRequest is never called and so we have requests hanging that don't do the same in 1.9.2
     
  29. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Tristan.fgol Just checked again my samples on an Android device, but they run fine.
    I would suggest to reinstall the plugin. If not already remove all TcpClientImplementation.dlls from the /Assets/Plugins/ folder.
    Also, you can enable a more chatty logging:
    Code (CSharp):
    1. BestHTTP.HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
     
  30. Muzako

    Muzako

    Joined:
    Mar 23, 2015
    Posts:
    4
    @BestHTTP , I have a nasty problem which I cant seem to find the solution after hours of trying and searching.
    When I make any HTTPRequest on the scene that the game started I have no problem, but when the scene changes in-game the callbacks of the request wont work.

    Every time I make a HTTPRequest on a scene that is not the one the game started it wont execute the callback, and in the console the only thing that appears(using Loglevels.All) is "I [HTTPConnection]: Connected to google.com" which is totally normal.

    Could you please help me?

    Thanks, Muzako.
     
  31. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Muzako I call a DontDestroyOnLoad on the GameObject that has the HTTPUpdateDelegater so it must be fine. Other than this, the plugin doesn't rely on Unity, or the current scene.
    I can reload or load other scenes while doing requests, wasn't able to reproduce it.

    After the ".. Connected to ..." line there should be an "... Sending request: ..." line too.

    Can you share more information? What version of the plugin and Unity are you using?

    But it would be the best if you can send me a repro project.
     
  32. Muzako

    Muzako

    Joined:
    Mar 23, 2015
    Posts:
    4

    Hi! Thanks for answering! So, I tried updating the asset(had the 1.7.8) and there's some improvement.
    The problem is still there, but the new version gives me some more info in the console:

    Code (CSharp):
    1. Console Log: Wed, Oct 28 12:59
    2.  
    3. Log (12:58:53.2452)
    4. Getting Token..
    5.   Stack Trace:
    6.   LaravelUtilities.GetToken()
    7.   Scripts/HTTP/LaravelUtilities.cs: line 107
    8.   JoinHost.Join()
    9.   Scripts/Networking/JoinHost.cs: line 60
    10.   JoinHost.Join()
    11.   Scripts/Networking/JoinHost.cs: line 48
    12.   UnityEngine.EventSystems.EventSystem.Update()
    13.   None: line 0
    14.  
    15. Log (12:58:53.2467)
    16. I [HTTPConnection]: Connected to 192.168.1.2:80
    17.   Stack Trace:
    18.  
    19. Log (12:58:53.2467)
    20. I [HTTPRequest]: Sending request: POST /ingame/gentoken/ HTTP/1.1
    21.   Stack Trace:
    22.  

    And this is my function:
    Code (CSharp):
    1. public void GetToken()
    2.   {
    3.   LaravelUtilities.CurrentUser._token = null;
    4.   HTTPRequest request_token = new HTTPRequest(new Uri("http://192.168.1.2" + "/ingame/gentoken/"), HTTPMethods.Post, (req, resp) =>
    5.   {
    6.   if (resp.StatusCode == 200)
    7.   {
    8.   Debug.Log("Recieved token: " + resp.DataAsText);
    9.  
    10.   LaravelUtilities.CurrentUser._token = resp.DataAsText;
    11.   }
    12.   else
    13.   {
    14.   Debug.Log(resp.DataAsText);
    15.   }
    16.   });
    17.  
    18.   request_token.AddField("_token", LaravelUtilities.token);
    19.   request_token.AddField("X-CSRF-TOKEN", LaravelUtilities.token);
    20.   Debug.Log("Getting Token..");
    21.   request_token.Send();
    22.   }
    The page does work, I tested it using a POST tester in Firefox. And if I call the exact same function on the first scene it works perfectly..


    Thanks, Muzako.
     
  33. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Muzako Is it reproducable in a completely new project too? And with a public server? (You can use http://httpbin.org as a test server.)
    If so, can you send that project to me? It would be extremely helpful to have a sample that i can debug.
     
  34. Muzako

    Muzako

    Joined:
    Mar 23, 2015
    Posts:
    4
    I was able to reproduce the problem in a new project.

    Thanks, Muzako.
     

    Attached Files:

  35. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Muzako Thanks for the repro-project.
    1.) Downloaded the latest version of the plugin from the Asset Store.
    2.) The Scene2 scene doesn't referenced the NewScene script, so i attached it to one of the objects.
    3.) After i start, i get the expected result, it will log out the "WORK!" string:
    upload_2015-10-28_21-38-41.png

    I used the same Unity version you used (5.0.0f4) and tried out my Pro and Basic versions too. I didn't have any idea what can be wrong on your side, or what we should try out. (Although I would recommend you very much to update your Unity installation!)
     
  36. Muzako

    Muzako

    Joined:
    Mar 23, 2015
    Posts:
    4
    ..well. I will try updating Unity, see if that changes something.
    Thanks for everything!
     
  37. Onsterion

    Onsterion

    Joined:
    Feb 21, 2014
    Posts:
    211
    Hi!

    How can I do for POST a Stream image

    Code (CSharp):
    1. byte[] image = faceTexture.EncodeToJPG();
    2. Stream imageStream = new MemoryStream(image);
    3.  
    4. var request = new HTTPRequest(new Uri(requestUrl), HTTPMethods.Post, OnRequestFinished);
    5.         request.SetHeader("Content-Type", "application/json; charset=UTF-8");
    6.         request.RawData = image;
    7.         request.Send();
    8.  

    I get:

    StatusCode: 400
    Bad Request
     
    Last edited: Nov 2, 2015
  38. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @Onsterion Well, you can set the request's UploadStream property:
    Code (CSharp):
    1. request.UploadStream = new MemoryStream(faceTexture.EncodeToJPG());
    But for this case setting the RawData would produce less memory garbage(you can skip constructing the MemoryStream):
    Code (CSharp):
    1. request.RawData = faceTexture.EncodeToJPG();
    Edit: The full POST request would look like this:
    Code (CSharp):
    1. var request = new HTTPRequest(new Uri("http://httpbin.org/post"), HTTPMethods.Post, (req, resp) =>
    2.     {
    3.         switch (req.State)
    4.         {
    5.             // The request finished without any problem.
    6.             case HTTPRequestStates.Finished:
    7.                 if (resp.IsSuccess)
    8.                 {
    9.                     Debug.Log("Request Finished Successfully! Data length: " + resp.Data.Length + " " + resp.DataAsText);
    10.                 }
    11.                 else
    12.                     Debug.LogWarning(string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
    13.                                                     resp.StatusCode,
    14.                                                     resp.Message,
    15.                                                     resp.DataAsText));
    16.                 break;
    17.  
    18.             // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
    19.             case HTTPRequestStates.Error:
    20.                 Debug.LogWarning("Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
    21.                 break;
    22.  
    23.             // The request aborted, initiated by the user.
    24.             case HTTPRequestStates.Aborted:
    25.                 Debug.LogWarning("Request Aborted!");
    26.                 break;
    27.  
    28.             // Ceonnecting to the server is timed out.
    29.             case HTTPRequestStates.ConnectionTimedOut:
    30.                 Debug.LogError("Connection Timed Out!");
    31.                 break;
    32.  
    33.             // The request didn't finished in the given time.
    34.             case HTTPRequestStates.TimedOut:
    35.                 Debug.LogError("Processing the request Timed Out!");
    36.                 break;
    37.         }
    38.     });
    39.  
    40. request.UploadStream = new MemoryStream(faceTexture.EncodeToJPG());
    41. request.Send();
     
  39. Onsterion

    Onsterion

    Joined:
    Feb 21, 2014
    Posts:
    211

    Wow! Thanks for the quick response and the example!

    It's Works!
     
  40. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    681
    I'm having an issue where all requests seem to get stuck on processing - resulting in them timing out. The weird thing is that this only happens for the first minute or so (in the editor). After waiting for a minute, all requests will work. (The very same, identical requests as those who failed.)

    I'm on Unity 5.1.3 and BestHTTP 1.9.4.

    Any ideas?
     
    Last edited: Nov 5, 2015
  41. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @SunnySunshine What version of Unity and the plugin are you using? In the editor are you using it in editor mode, or in play mode(after you press the play button)?
    Are you able to reproduce it using the samples using the SampleSelector scene in the /Examples/ folder?
     
  42. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    681
    I'm on Unity 5.1.3 and BestHTTP 1.9.4.

    The samples work fine.

    I'm in play mode.

    I noticed I only have this problem for requests using https. http requests will work right away. (The samples, even though using https, work fine too.)

    It's a really strange issue because it's just requests for the first minute, for the first times, that don't work. If I run the scene again, it's gonna work. But after opening the project, and doing these requests, they won't work the first couple of times.
     
  43. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @SunnySunshine Downloading Unity 5.1.3 right now. Can you send me the https urls that doesn't work?
    Have you checked functioning in builds? Hopefully it's something that reproducable in the editor only...
     
  44. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    681
    This is the code I'm using:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using BestHTTP;
    4.  
    5. public class HTTPTest : MonoBehaviour
    6. {
    7.     void Start ()
    8.     {
    9.         StartCoroutine(RequestCoroutine());
    10.     }
    11.  
    12.     private IEnumerator RequestCoroutine()
    13.     {
    14.         var req = new HTTPRequest(new System.Uri("https://www.google.com"), HTTPMethods.Get);
    15.  
    16.         req.Timeout = System.TimeSpan.FromSeconds(20);
    17.  
    18.         req.Send();
    19.  
    20.         Debug.Log("Request sent");
    21.  
    22.         yield return StartCoroutine(req);
    23.  
    24.         Debug.Log("Request finished");
    25.     }
    26. }
    This code will not work in a clean scene in my project. Using it in a completely new project does work however. Or changing the https to http.

    I have such a hard time understanding what's wrong. I'm trying to play around with different project settings but so far no luck.

    Remember, this only happens for the first 60-ish seconds.
     
  45. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @SunnySunshine Thanks.
    Unfortunately, I wasn't able to reproduce it yet.

    One thing that you can try out however:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using BestHTTP;
    4.  
    5. public class HTTPTest : MonoBehaviour {
    6.   void Start() {
    7.     HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
    8.     StartCoroutine(RequestCoroutine());
    9.   }
    10.  
    11.   private IEnumerator RequestCoroutine() {
    12.     var req = new HTTPRequest(new System.Uri("https://www.google.com"), HTTPMethods.Get);
    13.     req.UseAlternateSSL = true;
    14.  
    15.     req.Timeout = System.TimeSpan.FromSeconds(20);
    16.  
    17.     req.Send();
    18.  
    19.     Debug.Log("Request sent");
    20.  
    21.     yield return StartCoroutine(req);
    22.  
    23.     Debug.Log("Request finished");
    24.   }
    25. }
    It will use the alternate SSL/TLS handler, and will log out some information too.
     
  46. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    681
  47. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @SunnySunshine Thank you for the repr-project. I was able to reproduce it using Unity 5.1.3.f1. However the problem should be in Unity's mono implementation as there are two problems that i can't work on. The first was that the connection timed out, and the second one was processing the SSL/TLS certificates.

    But with latest Unitye release it's worked fine, and i wasn't able to reproduce it.
     
  48. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    681
    @BestHTTP

    Ok, thanks. Unfortunately we cannot upgrade to 5.2.x right now because of regression bugs, so we'll have to wait before we start to use BestHTTP. It seems like a really great product though, so we'll keep it.

    We've been having several users complain about network not working when using WWW, and we think BestHTTP will solve that. So we're very keen to upgrade to it once we have a Unity version that's compatible.

    Thanks for looking into the issues we were having.
     
  49. AwDogsGo2Heaven

    AwDogsGo2Heaven

    Joined:
    Jan 17, 2014
    Posts:
    102
    Hi is there anyway with BestHTTP or Unity to see how much data is being transferred total? I'm working on a mobile game and seeing this information in the editor would be really useful for me.
     
  50. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,411
    @AwDogsGo2Heaven Don't know any. Indeed, it would be really helpful.
     
unityunity