Search Unity

Best HTTP Released

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

  1. LR-Developer

    LR-Developer

    Joined:
    May 5, 2017
    Posts:
    109
  2. rreynoldsea

    rreynoldsea

    Joined:
    Apr 8, 2019
    Posts:
    2
    I see now that BestHTTP supports SSE out of the box. Not being familiar, I had the technologies confused. And reading the docs now. Thanks again for the help!
     
    Last edited: Apr 10, 2019
  3. BrandonSandersInContext

    BrandonSandersInContext

    Joined:
    Sep 25, 2015
    Posts:
    2
    @BestHTTP

    TL;DR Do you have advice for configuring BestHTTP to be proxy aware?

    I am debugging a problem with our application not working on user machines when they are using a proxy. I do not have information on the details of their proxy configuration.

    I have set up a VM, separate from my test machine, to run as a proxy. I update my test machine LAN Settings to use the proxy server. When I shut off the proxy, most applications on my machine are no longer able to connect to the internet, as expected. Both of my unity client applications, one in Unity 5.2.1f1, another in Unity 2018.3.11f1, continue to work, seeming to ignore the proxy completely. To clarify, I do not want to debug using a proxy, I want to make sure my client application can handle user machine's with proxies.

    Cheers!
     
  4. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @BrandonSandersInContext

    The plugin doesn't support automatic proxy detection. It will try to connect directly to the server, or if a proxy is set per-request or globally it will connect to that proxy.
     
  5. BrandonSandersInContext

    BrandonSandersInContext

    Joined:
    Sep 25, 2015
    Posts:
    2
    @BestHTTP

    I included code in the HTTPManager constructor to assign to the Proxy.

    Code (CSharp):
    1. var proxy = WebRequest.GetSystemWebProxy() as WebProxy;
    2.             var creds = proxy.Credentials as NetworkCredential;
    3.             Proxy = new HTTPProxy(proxy.Address, creds == null ? null : new Credentials(creds.UserName, creds.Password));
    I was able to confirm this does indeed detect the proxy I am expecting. I set breakpoints as far as I could understand to see BestHTTP attempt to connect to the proxy. My confusion is that I can turn off the proxy server, all other network requests on my machine will fail, but BestHTTP requests will continue to succeed. Do you have ideas as to what is causing this?
     
  6. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @BrandonSandersInContext

    It's because the plugin uses plain old tcp channels to connect to the server. Because the system just can't know what the application is doing with these sockets, it can't push them through the system-wide proxy. So these connections are just don't go through the proxy by default.
    On the other hand, applications who are using system-provided methods to do http, or if they can detect and use the system-set proxy, will fail to connect when the proxy is down.
     
  7. Samhayne

    Samhayne

    Joined:
    Jun 15, 2009
    Posts:
    45
    @BestHTTP
    We tried out Unity 2019.1f2's exciting new WebGL threading feature [Release Blog] [Forum-Thread] today for our project and we got it running so far.

    Unfortunately it looks like BestHttp's web sockets won't send any messages any more with threading enabled.
    The socket seems to be open (IsOpen() returns true when debugging the invoked Send() method) but the server never receives any data.

    As soon as I disable threading and do another WebGL build everything works fine again.
     
  8. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @Samhayne

    Are you enabled threading support in your browser? For webgl builds the plugin doesn't try to use any threads, so enabling threading support shouldn't cause problems.
    Of course I'm going to try to reproduce it and fix any issues.
     
  9. Samhayne

    Samhayne

    Joined:
    Jun 15, 2009
    Posts:
    45
    @BestHTTP
    Hey :)
    Thank you for your fast response!

    Yipp, I set those browser flags mentioned in the first posting of that forum thread I linked and (after some troubleshooting) eventually our project started fine.

    But then there seemed to be no web socket message going out any more with threading enabled... HTTP requests were still received but the web socket didn't seem to ever send data although everything looked fine from outside.

    If I'm right, placing this script in an Editor folder of your project...
    https://gist.github.com/mtrive/01374844278d2ec377c7f6bbc4df4e6a
    ... and doing a WebGL build should cause the mentioned issue.

    When I set...
    PlayerSettings.WebGL.threadsSupport = false
    ... data was sent again.
     
    Last edited: Apr 16, 2019
  10. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @Samhayne

    I just tried it out, but it worked as expected:
    upload_2019-4-18_8-54-19.png

    Enabled threading support in the browser and for the webgl build too.
    Could you send the console log?
    You can also set the plugin's log level to verbose with the following line:
    Code (CSharp):
    1. BestHTTP.HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
     
  11. Samhayne

    Samhayne

    Joined:
    Jun 15, 2009
    Posts:
    45
    @BestHTTP
    Thanks a lot for looking into this.

    My apologies for bothering you with this problem - if it works on your side something has to be funky on our side.

    Didn't get to the bottom of it yet but... due to whatever reason the connection seems to get lost - although websocket.IsOpen() says otherways.
    I set the log level as you said but everything seems to be alright.

    Due to some major changes in our project I don't know if I get the time to investigate this further right now but if I find out anything I'll write an update.

    Thanks again for your support and sorry again for the (probably) false alarm and taking your time.
     
  12. waldgeist

    waldgeist

    Joined:
    May 6, 2017
    Posts:
    388
    I'm using Best HTTP Pro in combination with WebSockets on mobile devices. If my app goes to the background on iOS, the WebSockets connection is cut off and throws an error if the app comes back to the foreground. Is there a way to tell the framework to auto-reconnect the WebSocket?
     
  13. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
  14. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @waldgeist

    The websocket protocol has no auto-reconnection, you have to do it manually.
     
  15. SteveJP87

    SteveJP87

    Joined:
    Feb 5, 2013
    Posts:
    15
    Hey there.

    Downloaded BestHTTP into a fresh project this morning and Unity is throwing compile errors.
    Assets\Best HTTP (Pro)\BestHTTP\SecureProtocol\crypto\tls\LegacyTlsAuthentication.cs(16,41): error CS0535: 'LegacyTlsAuthentication' does not implement interface member 'TlsAuthentication.GetClientCredentials(CertificateRequest)'

    There is also another error in the same class inside the NotifyServerCertificate function
    serverCertificate.GetCertifateList() cannot convert from Org.BouncyCastle.Asn1.X509.X509CertificateStructure[] to BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509.X509CertificateStructure[]


    I deleted the cached version of BestHTTP from my machine in-case there was a versioning conflict and downloaded it fresh from the AssetStore and this error persists.


     
  16. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @spanagiotis

    It's a project containing only the plugin, or there are other plugins too?
    I had no problem importing the plugin into an fresh and empty project.
     
  17. SteveJP87

    SteveJP87

    Joined:
    Feb 5, 2013
    Posts:
    15
    Aha.
    Looks like there is a conflict between GameSparks & BestHTTP. Seems they did not namespace their TlsAuthentication interface and it's being used over yours. Easily fixed on my end. Thank you!
     
  18. bravopooper

    bravopooper

    Joined:
    Jan 10, 2018
    Posts:
    1
    @BestHTTP

    I'm having a problem with socket.io connections not being closed properly when mobile devices lose network connection. The same thing happens when the app is paused and resumed multiple times, despite calling SocketManager.Close() when the application is paused and creating a new connection on resume.

    Due to the connection state not being reset, it's hitting the HTTPManager.MaxConnectionPerServer limit and any connections beyond that are failing.

    What would be the best way for this to be fixed? Any suggestions on how to investigate this?
     
  19. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @bravopooper

    What version of the plugin are you using?
    Could you send logs after you set the plugin's log level to verbose? You can set it like this somewhere in your startup code:
    Code (CSharp):
    1. BestHTTP.HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
     
  20. Filipinjo

    Filipinjo

    Joined:
    Jan 7, 2014
    Posts:
    22
    Hello there! I have a problem with this error:
    Can't assign value '-5,5' (type System.Double) to type System.Single

    I've registered your importer from previous posts like this:
    JsonMapper.RegisterImporter<double, int>((input) => (int)(input + 0.5));

    I'd really appreciate some help :)
     
  21. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @Filipinjo

    According to that error message, it wants to convert from Double to Single(float). A new importer might do the trick:
    Code (CSharp):
    1. JsonMapper.RegisterImporter<double, float>((input) => (float)input);
     
    Filipinjo likes this.
  22. Filipinjo

    Filipinjo

    Joined:
    Jan 7, 2014
    Posts:
    22
    Thank you very much! It works :D You're awesome!
     
  23. OlehMekhedok

    OlehMekhedok

    Joined:
    Jan 17, 2019
    Posts:
    2
    I encountered with problem, I try to POST few fields to server using HttpRequst, in editor works perfectly but on webgl for some reason post method changing to OPTIONS
    Maybe somebody has sugestions?
     
    Last edited: May 3, 2019
  24. OlehMekhedok

    OlehMekhedok

    Joined:
    Jan 17, 2019
    Posts:
    2
  25. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
  26. phylong

    phylong

    Joined:
    Nov 15, 2014
    Posts:
    2
    i use httprequest to download large file,but the speed is too slow than safari.is there anything i can do optimize?
     
  27. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @phylong

    Are you downloading over HTTPS? If so, the bottleneck is the TLS handler's (BouncyCastle in this case) decryption. Unfortunately BouncyCastle wasn't implemented performance in mind.
    But, you can try out the .net framework's SslStream implementation by flipping a flag:
    Code (CSharp):
    1. BestHTTP.HTTPManager.UseAlternateSSLDefaultValue = false;
     
  28. phylong

    phylong

    Joined:
    Nov 15, 2014
    Posts:
    2
    I used the code, but the download will get a null response, and downloading will be failed.
    my editor version is 2017.4.26,and script runtime version is 4.6
    the content is from:
    https://public.boxcloud.com/d/1/b1!...85zEnwuKh1A3aHqtVX1nffhfXmdN5gtZ5WZU/download
     
  29. yanlevesque

    yanlevesque

    Joined:
    Mar 15, 2018
    Posts:
    2
    I would like to know where your plans for http/2 are on your todo list more than a year ago. :)
     
  30. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
  31. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @yanlevesque

    It's sits almost on top of the list. Currently slowly rewriting large part of the plugin to be able to add the http/2 support.
     
    Cromfeli likes this.
  32. gagarin-interactive

    gagarin-interactive

    Joined:
    Aug 26, 2015
    Posts:
    4
    Hi,

    Thank you for this plugin. I was up and running with a ws client in minutes.

    Can this plugin act as a websocket server or just a client?

    I have a Unity app and a web app ( localhost ) that need to communicate via websocket. Would you reccomend setting up a local websocket server to sit in between the two application?

    Best
     
  33. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @gagarin-interactive

    No, the plugin act as a client only.
    If not necessary, i wouldn't recommend to add a new layer between the two applications.
     
  34. gagarin-interactive

    gagarin-interactive

    Joined:
    Aug 26, 2015
    Posts:
    4
    Thanks.

    But how would two clients communicate? One of the applications has to be a server - right?
     
  35. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @gagarin-interactive

    I think I misunderstood your setup and what you want to achieve, but what's your local web app is for? If you want that two or more clients communicate you need a main server that all of them can connect to. All communication is done through this server and you could avoid a lot of headache.
     
  36. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    New version is out in the asset store!

    This release is part of a series to drive away from hard locks and to prepare for a possible http/2 implementation.

    Changlelog of v1.12.0:
    1.12.0 (2019.05.28)
    • General
      • [Improvement] Part of a larger code rewrite/overhaul removed a lot of locks and added lock-free collections and/or using ReaderWriterLockSlim. These changes affect all parts of the plugin from cookies to the signalr core protocol.
      • [Bugfix] Fixed a bug in the protocol upgrade callback to do not overwrite the connection's previously set state
      • [New Feature] HTTPRequest now supports the async-await pattern when CSHARP_7_OR_LATER is declared by Unity3d
      • [Improvement] HTTPManager.TryToMinimizeTCPLatency's default value became true
      • [Improvement] HTTPManager.MaxConnectionPerServer's default value became 6
    • SignalRCore
      • [Bugfix] JSonProtocol now handles enums properly
      • [Improvement] JSonProtocol now can handle nullable types
    • Server-Sent Events
      • [New Feature] Example added
     
    Last edited: May 31, 2019
    Cromfeli likes this.
  37. crevelop

    crevelop

    Joined:
    Nov 9, 2010
    Posts:
    13
    Hi, I've been using your plugin to connect a Unity (iOS and Android) app to a SignalRCore server.

    It's been working great, except that the app is getting constant HUB disconnection errors every 30 seconds (regardless of interaction)

    I can replicate it in the Unity Editor with same time interval too. This is the error message:

    Request Finished with Error! Exception: TCP Stream closed unexpectedly by the remote server

    Anything to do with the client/plugin configuration?
    Am I missing something in my SignalRCore server instead for this not to drop the connection constantly?
     
  38. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @crevelop

    First i would recommend to check your server configuration, it might closes connections after a specific time.
    Also, while the client doesn't limit connection time, you can set the plugin's log level and send to me:
    Code (CSharp):
    1. BestHTTP.HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
     
  39. berry4u

    berry4u

    Joined:
    Dec 27, 2017
    Posts:
    30

    I have exactly the same issue on Connecting with error "Request Finished with Error! Exception: TCP Stream closed unexpectedly by the remote server at BestHTTP.WebSocket.Frames.WebSocketFrameReader.Read (System.IO.Stream stream)
    the error is generated in WebSocketFrameReader.cs:135

    Sent you the Log by email
     
    Last edited: May 30, 2019
  40. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @crevelop @berry4u

    Is this error happens after you upgraded to the new release or you are on an older one?
     
  41. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @berry4u

    PS. Clicking on console messages generated by debug.log I have an error (ArgumentOutOfRangeException: Length cannot be less than zero)

    I think that's a Unity console bug.
     
  42. berry4u

    berry4u

    Joined:
    Dec 27, 2017
    Posts:
    30
    I'm using 2019.1.0f2 and tested with the same issue on 2018.3.6f1.
    One more thing: with the same server I'm testing browser clients too (testing also cross platform origins). It works fine with every client in localhost on the contrary it throws the error when used on LAN only with BestHTTP Unity-based client.
     
  43. berry4u

    berry4u

    Joined:
    Dec 27, 2017
    Posts:
    30
    I agree :)
     
  44. crevelop

    crevelop

    Joined:
    Nov 9, 2010
    Posts:
    13
    Hey guys, all sorted out, issue was rather server-side in my case.

    Depending the kind of server you are running the KeepAliveInterval defaults can be different.

    For us, it was solved by setting it to 5 seconds within Startup.cs like this:

    Code (CSharp):
    1.  
    2.             services.AddSignalR(options =>
    3.             {
    4.                 options.KeepAliveInterval = TimeSpan.FromSeconds(5);
    5.             });
    6.  
    Hope this is helpful :)
     
  45. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @crevelop

    That's quite interesting, i have doubt that KeepAliveInterval alone had any effect, or you had a different problem what i seen in the logs berry4u sent to me. Either way, i'm happy that it solved your problem. :)
     
  46. Lost-in-the-Garden

    Lost-in-the-Garden

    Joined:
    Nov 18, 2015
    Posts:
    176
    @BestHTTP
    Hello!
    When I click on a Log from a websocket callback the unity Console is crashing (2019.1.0f2):

    Code (CSharp):
    1. ArgumentOutOfRangeException: Length cannot be less than zero.
    2. Parameter name: length
    3. System.String.Substring (System.Int32 startIndex, System.Int32 length) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
    4. UnityEditor.ConsoleWindow.StacktraceWithHyperlinks (System.String stacktraceText) (at C:/buildslave/unity/build/Editor/Mono/ConsoleWindow.cs:823)
    5. UnityEditor.ConsoleWindow.OnGUI () (at C:/buildslave/unity/build/Editor/Mono/ConsoleWindow.cs:740)
    6. System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
    7. Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
    8. System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
    9. System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
    10. UnityEditor.HostView.Invoke (System.String methodName, System.Object obj) (at C:/buildslave/unity/build/Editor/Mono/HostView.cs:345)
    11. UnityEditor.HostView.Invoke (System.String methodName) (at C:/buildslave/unity/build/Editor/Mono/HostView.cs:339)
    12. UnityEditor.HostView.InvokeOnGUI (UnityEngine.Rect onGUIPosition, UnityEngine.Rect viewRect) (at C:/buildslave/unity/build/Editor/Mono/HostView.cs:315)
    13. UnityEditor.DockArea.DrawView (UnityEngine.Rect viewRect, UnityEngine.Rect dockAreaRect, System.Boolean floatingWindow, System.Boolean isBottomTab) (at C:/buildslave/unity/build/Editor/Mono/GUI/DockArea.cs:373)
    14. UnityEditor.DockArea.OldOnGUI () (at C:/buildslave/unity/build/Editor/Mono/GUI/DockArea.cs:340)
    15. UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:295)
    16. UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:481)
    17. UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:464)
    18. UnityEngine.UIElements.IMGUIContainer.HandleEvent (UnityEngine.UIElements.EventBase evt) (at C:/buildslave/unity/build/Modules/UIElements/IMGUIContainer.cs:444)
    19. UnityEngine.UIElements.EventDispatchUtilities.PropagateEvent (UnityEngine.UIElements.EventBase evt) (at C:/buildslave/unity/build/Modules/UIElements/Events/IEventDispatchingStrategy.cs:64)
    20. UnityEngine.UIElements.MouseEventDispatchingStrategy.DispatchEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at C:/buildslave/unity/build/Modules/UIElements/Events/MouseEventDispatchingStrategy.cs:58)
    21. UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at C:/buildslave/unity/build/Modules/UIElements/EventDispatcher.cs:280)
    22. UnityEngine.UIElements.EventDispatcher.Dispatch (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, UnityEngine.UIElements.DispatchMode dispatchMode) (at C:/buildslave/unity/build/Modules/UIElements/EventDispatcher.cs:156)
    23. UnityEngine.UIElements.BaseVisualElementPanel.SendEvent (UnityEngine.UIElements.EventBase e, UnityEngine.UIElements.DispatchMode dispatchMode) (at C:/buildslave/unity/build/Modules/UIElements/Panel.cs:189)
    24. UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at C:/buildslave/unity/build/Modules/UIElements/UIElementsUtility.cs:255)
    25. UnityEngine.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C:/buildslave/unity/build/Modules/UIElements/UIElementsUtility.cs:78)
    26. UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C:/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179)
     
    Last edited: Jun 6, 2019
    LTPStudioXR likes this.
  47. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @Lost-in-the-Garden

    Unfortunately this is a Unity bug, already filled up and sent a bug report about it.
     
  48. andywatts

    andywatts

    Joined:
    Sep 19, 2015
    Posts:
    112
    Re. HTTPRequest now supports the async-await pattern when CSHARP_7_OR_LATER is declared by Unity3d

    Do you have an example?

    I tried "await request.Send();"
     
  49. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @andywatts

    Almost. Here's an example to download and print a string:
    Code (CSharp):
    1. using System;
    2. using System.Threading.Tasks;
    3. using UnityEngine;
    4.  
    5. using BestHTTP;
    6.  
    7. public class AsyncTest : MonoBehaviour
    8. {
    9.     async Task Start()
    10.     {
    11.         var request = new HTTPRequest(new Uri("https://httpbin.org/get"));
    12.  
    13.         Debug.Log(await request.GetAsStringAsync());
    14.     }
    15. }
    16.  
    New APIs are GetHTTPResponseAsync, GetAsStringAsync, GetAsTexture2DAsync, GetRawDataAsync and using LitJson from the Examples folder there's a GetFromJsonResultAsync.

    You can write your own extension. I think the GetFromJsonResultAsync in the \Best HTTP (Pro)\Examples\Plugin\AsyncExtensions.cs is a good example.

    Almost forgot, it supports CancellationTokens too:
    Code (CSharp):
    1. using System;
    2. using System.Threading;
    3. using System.Threading.Tasks;
    4. using UnityEngine;
    5.  
    6. using BestHTTP;
    7.  
    8. public class AsyncTest : MonoBehaviour
    9. {
    10.     async Task Start()
    11.     {
    12.         var request = new HTTPRequest(new Uri("https://httpbin.org/get"));
    13.  
    14.         CancellationTokenSource tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
    15.         Debug.Log(await request.GetAsStringAsync(tokenSource.Token));
    16.  
    17.         // don't forget to dispose! ;)
    18.         tokenSource.Dispose();
    19.     }
    20. }
    21.  
    And ConfigureAwait too:
    Code (CSharp):
    1. using System;
    2. using System.Threading;
    3. using System.Threading.Tasks;
    4. using UnityEngine;
    5.  
    6. using BestHTTP;
    7.  
    8. public class AsyncTest : MonoBehaviour
    9. {
    10.     async Task Start()
    11.     {
    12.         var request = new HTTPRequest(new Uri("https://httpbin.org/get"));
    13.  
    14.         CancellationTokenSource tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
    15.         Debug.Log(Thread.CurrentThread.ManagedThreadId);
    16.  
    17.         string result = await request.GetAsStringAsync(tokenSource.Token).ConfigureAwait(false);
    18.  
    19.         Debug.Log(Thread.CurrentThread.ManagedThreadId);
    20.         Debug.Log(result);
    21.  
    22.         // don't forget to dispose! ;)
    23.         tokenSource.Dispose();
    24.     }
    25. }
    26.  
     
    andywatts likes this.
  50. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    @andywatts

    Forgot to add, that errors are going to be exceptions with async-await, so it should be something like this:
    Code (CSharp):
    1.  
    2. try
    3. {
    4.     Debug.Log(await request.GetAsStringAsync(tokenSource.Token));
    5. }
    6. catch (Exception ex)
    7. {
    8.     Debug.LogException(ex);
    9. }
    10.  
     
    mbodekaer and andywatts like this.