Search Unity

Best HTTP Released

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

  1. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    The given Uri is not changed by the plugin, except when a redirection occures. The original Uri stored in the request's Uri property. When redirected, the last redirection Uri is in the RedirectUri. There is a CurrentUri property too, it's just a shortcut to return the RedirectUri if redirected, or the original Uri otherwise.

    You can use the DumpHeaders() functions to get a string that contains what headers and header values will be sent to the server:

    Code (CSharp):
    1. string headers = request.DumpHeaders();
    2. Debug.Log(headers);
    But, for more easier and precise debugging i would recommend using an immediate proxy.
    In BestHTTP you can set a global proxy(HTTPManager.Proxy = new HTTPProxy(....) ; ) that all requests will use, so you have to set it once, and you can see what request are mode to the server in the proxy's window.
    I recommend Charles(http://www.charlesproxy.com/) but Fiddler(http://www.telerik.com/fiddler) is good too. You can install these on your computer, set the Proxy property in your game and you will see what requests and responses are go through.
     
    Last edited: Feb 6, 2015
  2. Xemenas

    Xemenas

    Joined:
    Sep 10, 2012
    Posts:
    28
    Oh thank you! I'll give one of those a try.
     
  3. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    New update uploaded to the Asset Store with improvements and new samples.

    The release notes of the update:
    • [Improvement] Custom cookies can be added to a HTTPRequest. More on this in the documentation
    • [Improvement] Queued requests can be aborted too
    • [Improvement] GetGeneralStatistics function added to the HTTPManager. This function will return a GeneralStatistics struct that contains infromations about connections, cache and cookies.
    • [Improvement] HTTPRequest’s Callback can be set to a new value after the request’s State is changed
    • [Improvement] New code samples with a demo-browser! Check it out live here: http://bit.ly/1AkM6gi
      • Texture Download Sample
      • Asset Bundle Download Sample
      • Large File Download Sample
      • WebSocket - Echo Sample
      • Socket.IO - Chat Sample
      • Socket.IO - WePlay Sample
      • Cache Maintenance Sample
     
  4. Hitman666

    Hitman666

    Joined:
    Dec 20, 2014
    Posts:
    4
    Hi,

    I'm using Unity3D free, and I was planing to buy your asset (pro) to give me Socket.IO support for my game server written in Node.js. However, I saw that Good ol' sockets are required with your plugin, and I've read on their docs this: "It is also possible to revert the patching process. This is sometimes required when you want to build for a platform that is not supported by Good ol’ Sockets (Web Player or Windows Phone, for example)."

    Does this mean that if I use your asset + Good ol' sockets I won't be able to export to the web player?

    Thanks,
    Nikola
     
  5. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    No, I think it's just means that you have to use the "Revert back to original ..." menu item before you build for WebPlayer, then patch it again when you finished and you want to build for an other platform(that would require Unity Pro).
     
  6. Hitman666

    Hitman666

    Joined:
    Dec 20, 2014
    Posts:
    4
    Hmm, is there any way to test this? I wouldn't want to be in a position that I buy two assets (together 75+€) worth and that then they don't work they way I need them to.
     
  7. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Send me your email address in private, and will send you a version to test.
     
  8. ZimM

    ZimM

    Joined:
    Dec 24, 2012
    Posts:
    963
    It'll work just fine as @BestHTTP said:
    So yes, it will work on both WebPlayer and iOS/Android without any problems, but you'll have to do some patching/reverting back and forth when switching platforms. That might be a bit of annoyance if you are making builds frequently, but I believe it's not that much of a deal.
     
  9. Hitman666

    Hitman666

    Joined:
    Dec 20, 2014
    Posts:
    4
    Thanks to both of you guys for your help and clarifications!
     
  10. sayangel

    sayangel

    Joined:
    Apr 11, 2014
    Posts:
    12
    Really interested in purchasing this, but I have to ask... how's the large file download on mobile? I've had a TERRIBLE experience with WWW and mobile. A 12 mb file takes minutes to download. Does BestHTTP get around this?

    I noticed on the webplayer it was pretty smooth. Would love to hear how the Android performance is before I purchase.

    Thanks!
     
  11. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Ther are no intentional delays in the plugin. It will try to dispatch the downloaded data as soon as possible. You can wait to download the whole data(UseStreaming = false), or you can start to process the data while downloading it(UseStreaming = true). The demo made with UseStreaming = true, to be able to save the position and continue the download if needed. You can still feed the downloaded data to a MemoryStream to get it as a whole.

    On the same network, i experience equally good download performance on mobile and pc too(tested on WP, Android, iOS and PC), but still, it can't circumvent bad networks.
     
  12. TinyMobGraham

    TinyMobGraham

    Joined:
    Oct 17, 2013
    Posts:
    38
    Does BestHTTP work with Unity iOS 64 bit yet? It sounds like you've been working on support for IL2CPP, but I get an error when I try to build our project with BestHTTP in Unity 4.6.2 with IL2CPP. Your documentation says "iOS Stripping is unsupported currently" - doesn't that mean it won't work with the Unity IL2CPP 64 bit compilation process? Or should it work?

    Here is the error I get when I try to build in Unity 4.6.2 with IL2CPP:

    UserBlackList: .../Assets/Best HTTP (Pro)/link.xml
    Invoking UnusedByteCodeStripper2 with arguments: -out ".../Temp/StagingArea/Data/Managed" -l none -c link -x "/Applications/Unity/Unity.app/Contents/Frameworks/Tools/UnusedByteCodeStripper/native_link.xml" -f "/Applications/Unity/Unity.app/Contents/Frameworks/il2cpp/LinkerDescriptors" -x ".../Temp/StagingArea/Data/Managed/../platform_native_link.xml" -x ".../Temp/StagingArea/Data/methods_pointedto_by_uievents.xml" -x ".../Assets/Best HTTP (Pro)/link.xml" -d ".../Temp/StagingArea/Data/Managed" -a ".../Temp/StagingArea/Data/Managed/Assembly-CSharp.dll" -a ".../Temp/StagingArea/Data/Managed/Assembly-CSharp-firstpass.dll" -a ".../Temp/StagingArea/Data/Managed/Assembly-UnityScript.dll"
    Failed running /Applications/Unity/Unity.app/Contents/Frameworks/Tools/UnusedByteCodeStripper2/UnusedBytecodeStripper2.exe -out ".../Temp/StagingArea/Data/Managed" -l none -c link -x "/Applications/Unity/Unity.app/Contents/Frameworks/Tools/UnusedByteCodeStripper/native_link.xml" -f "/Applications/Unity/Unity.app/Contents/Frameworks/il2cpp/LinkerDescriptors" -x ".../Temp/StagingArea/Data/Managed/../platform_native_link.xml" -x ".../Temp/StagingArea/Data/methods_pointedto_by_uievents.xml" -x ".../Assets/Best HTTP (Pro)/link.xml" -d ".../Temp/StagingArea/Data/Managed" -a ".../Temp/StagingArea/Data/Managed/Assembly-CSharp.dll" -a ".../Temp/StagingArea/Data/Managed/Assembly-CSharp-firstpass.dll" -a ".../Temp/StagingArea/Data/Managed/Assembly-UnityScript.dll"

    stdout;
    ERROR: Failed to resolve base type System.Configuration.ConfigurationException for type System.Configuration.ConfigurationErrorsException
    Fatal error in Mono CIL Linker
    System.Exception: ERROR: Failed to resolve base type System.Configuration.ConfigurationException for type System.Configuration.ConfigurationErrorsException
    at UnusedBytecodeStripper2.ResolveFromMonoBehaviours.IsMonoBehaviourOrScriptableObject (Mono.Cecil.TypeDefinition type) [0x00000] in <filename unknown>:0
    at System.Linq.Enumerable+<CreateWhereIterator>c__Iterator35`1[Mono.Cecil.TypeDefinition].MoveNext () [0x00000] in <filename unknown>:0
    at UnusedBytecodeStripper2.ResolveFromMonoBehaviours.Process (Mono.Linker.LinkContext context) [0x00000] in <filename unknown>:0
    at Mono.Linker.Pipeline.Process (Mono.Linker.LinkContext context) [0x00000] in <filename unknown>:0
    at Mono.Linker.Driver.Run () [0x00000] in <filename unknown>:0
    at Mono.Linker.Driver.RunDriver (Mono.Linker.Driver driver) [0x00000] in <filename unknown>:0
    stderr:

    UnityEngine.Debug:Internal_Log(Int32, String, Object)
    UnityEngine.Debug:LogError(Object)
    UnityEditorInternal.Runner:RunManagedProgram(String, String, String, CompilerOutputParserBase)
    UnityEditorInternal.AssemblyStripper:RunAssemblyLinker(IEnumerable`1, String&, String&, String, String)
    UnityEditorInternal.AssemblyStripper:StripAssembliesTo(String, String, String&, String&, String, String, IEnumerable`1)
    UnityEditorInternal.AssemblyStripper:Strip(String, String, String&, String&, String, String, IEnumerable`1)
    UnityEditorInternal.AssemblyStripper:Strip(String[], String[], String, String, String&, String&, String, String, IEnumerable`1)
    UnityEditorInternal.IL2CPPBuilder:RunAssemblyStripper(IEnumerable, String, String[], String[], String)
    UnityEditorInternal.IL2CPPBuilder:StripAssemblies(String[], String)
    UnityEditorInternal.IL2CPPBuilder:Run()
    UnityEditorInternal.IL2CPPUtils:RunIl2Cpp(String, String, IIl2CppPlatformProvider, Action`1, RuntimeClassRegistry)
    UnityEditor.iOS.PostProcessiPhonePlayer:postProcess(iOSBuildPostprocessor, BuildTarget, String, String, String, String, String, String, String, BuildOptions, RuntimeClassRegistry)
    UnityEditor.iOS.iOSBuildPostprocessor:postProcess(BuildPostProcessArgs)
    UnityEditor.PostprocessBuildPlayer:postprocess(BuildTarget, String, String, String, Int32, Int32, String, String, BuildOptions, RuntimeClassRegistry)
    UnityEditor.BuildPipeline:BuildPlayerInternalNoCheck(String[], String, BuildTarget, BuildOptions, Boolean, UInt32&)
    UnityEditor.BuildPlayerWindow:BuildPlayerWithDefaultSettings(Boolean, BuildOptions, Boolean)
    UnityEditor.BuildPlayerWindow:BuildPlayerWithDefaultSettings(Boolean, BuildOptions)
    UnityEditor.BuildPlayerWindow:GUIBuildButtons(Boolean, Boolean, Boolean, BuildPlatform)
    UnityEditor.BuildPlayerWindow:ShowBuildTargetSettings()
    UnityEditor.BuildPlayerWindow:OnGUI()
    System.Reflection.MonoMethod:InternalInvoke(Object, Object[], Exception&)
    System.Reflection.MonoMethod:Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222)
    System.Reflection.MethodBase:Invoke(Object, Object[]) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MethodBase.cs:115)
    UnityEditor.HostView:Invoke(String, Object)
    UnityEditor.HostView:Invoke(String)
    UnityEditor.HostView:OnGUI()

    (Filename: /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs Line: 222)

    Error building Player: Exception: /Applications/Unity/Unity.app/Contents/Frameworks/Tools/UnusedByteCodeStripper2/UnusedBytecodeStripper2.exe did not run properly!
     
  13. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664

    You can avoid the stripping error by setting the "Api Compatibility Level" to ".NET 2.0" in the Player Settings.
    However, there is one big issue with IL2CPP: we have to wait for a patch release for Socket support.

    EDIT: Of course, when the Socket will be supported in IL2CPP builds it should work, but i will test it too and make sure that my plugin works as expected as i already did some steps to workaround IL2CPP bugs.
     
    Last edited: Feb 17, 2015
  14. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
  15. desyashasyi

    desyashasyi

    Joined:
    Nov 22, 2012
    Posts:
    73
    Hii.. I am trying to create user log that sending data to the server. I create a Playmaker action just for testing as follows:
    Code (CSharp):
    1. sing UnityEngine;
    2. using BestHTTP;
    3. using System;
    4.  
    5. namespace HutongGames.PlayMaker.Actions
    6. {
    7.     [ActionCategory("Magnitude")]
    8.     [Tooltip("Send Data to Server")]
    9.     public class SendDataToHTTP : FsmStateAction
    10.     {
    11.         public FsmString url;
    12.  
    13.  
    14.         public override void Reset()
    15.         {
    16.  
    17.         }
    18.  
    19.         public override void OnEnter()
    20.         {
    21.             DoBuildField();
    22.          
    23.             Finish();
    24.         }
    25.  
    26.         public override void OnUpdate()
    27.         {
    28.             DoBuildField();
    29.  
    30.         }
    31.      
    32.         void DoBuildField()
    33.         {
    34.             HTTPRequest request = new HTTPRequest(new Uri(url.Value), HTTPMethods.Post, OnRequestFinished);
    35.             request.AddField  ("name", "myName");
    36.             request.Send();
    37.         }
    38.  
    39.  
    40.         void OnRequestFinished(HTTPRequest request, HTTPResponse response)
    41.         {
    42.         Debug.Log("Request Finished! Text received: " + response.DataAsText);
    43.         }
    44.  
    45.      
    46.     }
    47. }

    in the server i put this code:
    Code (php):
    1. <?php
    2.   if( $_POST["name"]
    3.   {
    4.      echo "Welcome ". $_POST['name']. "<br />";
    5.  
    6.      exit();
    7.   }
    8. ?>
    But It did not show the variable content. What is the problem.
     
  16. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Just tested your code, and it's working fine. I used two POST-test servers to test it:
    -httpbin.org/post returned:
    Code (csharp):
    1.  
    2. {
    3.   "args": {},
    4.   "data": "",
    5.   "files": {},
    6.   "form": {
    7.   "name": "myName"
    8.   },
    9.   "headers": {
    10.   "Accept-Encoding": "gzip, identity",
    11.   "Content-Length": "11",
    12.   "Content-Type": "application/x-www-form-urlencoded",
    13.   "Host": "httpbin.org",
    14.   "Te": "identity",
    15.   "User-Agent": "BestHTTP"
    16.   },
    17.   "json": null,
    18.   "origin": "5.187.236.190",
    19.   "url": "http://httpbin.org/post"
    20. }
    21.  
    -http://www.posttestserver.com/post.php (http://www.posttestserver.com/data/2015/02/22/23.59.521867720694):
    Post Params:
    key: 'name' value: 'myName'


    What response are you getting for you url?
     
  17. young-xyz

    young-xyz

    Joined:
    Feb 23, 2015
    Posts:
    51
    Hi. I purchased besthttp pro, and use it to post something.
    But it has some error when i try to send object array field.
    Httprequest object has that field correctly, but the server receive nothing. And no error message.
    My post code is very simple.
    Code (CSharp):
    1.  
    2.             HTTPRequest request = new HTTPRequest(new Uri(uri), HTTPMethods.Post);
    3.             request.AddField("json", post);
    4.             request.ConnectTimeout = TimeSpan.FromSeconds(2);
    5.             request.Timeout = TimeSpan.FromSeconds(10);
    6.             request.Send();
    7.             yield return StartCoroutine(request);
    8.  
    and my 'post' json string is:
    {"fNo":9,"recoSendObj":[{"rNo":1,"reco":0},{"rNo":2,"reco":0},{"rNo":3,"reco":0},...,{"rNo":15,"reco":0}]}

    I used JSON.NET to serialize object to this json string.
    I was using unity3d WWW class, it worked well.
    Should i do something to add object array field in besthttp?
     
  18. desyashasyi

    desyashasyi

    Joined:
    Nov 22, 2012
    Posts:
    73
    Hiii... perhaps the configuration of server is not suitable. I also try in localhost, same! just shows "welcome:" without variable content.
    I will try in another server. Thank
     
  19. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    It should work just fine. Can you post how you sent it with WWW?
    Also, for a workaround you may try to set the FormUsage to Unity for the request:
    Code (CSharp):
    1. request.FormUsage = BestHTTP.Forms.HTTPFormUsage.Unity;
    This will use internally Unity's WWWForm to encode the form data.
     
  20. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Tried your php code too. After added the missing ')' it worked as expected.
    Code (CSharp):
    1.         var request = new HTTPRequest(new Uri("http://testserver.com/test.php"), 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.         request.AddField("name", "myname");
    40.         request.Send();
     
  21. young-xyz

    young-xyz

    Joined:
    Feb 23, 2015
    Posts:
    51
    It's simple.

    Code (CSharp):
    1.             WWWForm form = new WWWForm ();
    2.             form.AddField("json", post);
    3.             WWW www = new WWW (url, form);
    and it works well with setting FormUsage. Thanks!
     
  22. Zaddo67

    Zaddo67

    Joined:
    Aug 14, 2012
    Posts:
    489
    Will BestHTTP allow me to make ajax type calls to a MVC webservice on IIS?

    something like the following javascript with a callback function (But preferrably coded in C# within unity).

    Code (csharp):
    1.  
    2. $.ajax({
    3. url:'GameService/GetGames',
    4. data:"{}",
    5. dataType:"json",
    6. type:"GET",
    7. contentType:"application/json; charset=utf-8",
    8. success: successFunction
    9. });
    10.  
    I am comfortable developing websites using ASP.NET, but I only have a surface knowledge of the underlying technology. So I don't know if it is possible to connect to these webservices with a tool like BestHTTP.

    If so, are there any examples?
     
    Last edited: Feb 23, 2015
  23. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    I don't have any experience with ajax and MVC webservices, but all of these are based on regular http requests. One of my old demo's service side was written in ASP. Net Web Api 2:
    Code (CSharp):
    1. public class LeaderBoardTestController : ApiController
    2. {
    3.     //
    4.     // GET api/LeaderBoardTest?from={0}&count={1}
    5.     public HttpResponseMessage Get(int from, int count)
    6.     {
    7.         var resp = new HttpResponseMessage(HttpStatusCode.OK);
    8.         resp.Content = new PushStreamContent(async (outStream, content, context) =>
    9.         {
    10.             try
    11.             {
    12.                 for (int i = 0; i < count; ++i)
    13.                 {
    14.                     byte[] buffer = System.Text.Encoding.UTF8.GetBytes(string.Format("Player_Name_{0};{1}\n", from + i, from + count - i));
    15.                     await outStream.WriteAsync(buffer, 0, buffer.Length);
    16.                     System.Threading.Thread.Sleep(500);
    17.                 }
    18.             }
    19.             finally
    20.             {
    21.                 outStream.Close();
    22.             }
    23.         });
    24.  
    25.         resp.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue();
    26.         resp.Content.Headers.Add("Expires", DateTime.Now.AddSeconds(60).ToUniversalTime().ToString("R"));
    27.  
    28.         return resp;
    29.     }
    30. }
    And a trivial request to this service would be the following:
    Code (CSharp):
    1. var request = new HTTPRequest(new Uri(string.Format("http://besthttp.azurewebsites.net/api/LeaderboardTest?from={0}&count={1}", from, count)), OnLeaderboardArrived);
    2. request.Send();
    Other types of request are similiarly easy.
     
  24. Zaddo67

    Zaddo67

    Joined:
    Aug 14, 2012
    Posts:
    489
    Wow, fast response, thx :)

    In your example you are using await. Is it possible to use a callback when the server responds?

    I am a bit of a Asset store junkie. I just checked and I actually own BestHTTP Pro :) I must have picked it up in a sale.

    SInce I own it, I will have a play :)

    Thx.
     
  25. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    The callback function is the last param of the HTTPRequest constructor(it's hard to miss on my example with that long url :) ).
    This callback is called when the plugin processed the server response, or when an error occurs. It has two parameters: the original request object and a response object containing the server's response. The response might be null on errors.
     
  26. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    A little service message: battling with flu i have high fever now, so my answers might be disorganized a little, but i will do my best. Thank you for your understanding.
     
  27. desyashasyi

    desyashasyi

    Joined:
    Nov 22, 2012
    Posts:
    73
    Hiii... Thank you for helping me to find out the problem. I have tried many server, i.e localhost using xampp in macbook, and also i tried in free hosting. But I have no luck. Actually, with same code that i posted before, in unity project i got this log, but web site did not show anything. can you look at deewahyu.honor.es. ooo it is pain :). Could you suggest me what is the problem? is it in php configuration?

    here is the console log. It is show, that the script in www already get parameter from playmaker action.

    Request Finished! Text received: Welcome Didin<br />
    UnityEngine.Debug:Log(Object)
    HutongGames.PlayMaker.Actions.SendDataToHTTP:OnRequestFinished(HTTPRequest, HTTPResponse) (at Assets/Magnitude/Scripts/Playmaker/SendDataToHTTP.cs:47)
    BestHTTP.HTTPRequest:CallCallback() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPRequest.cs:794)
    BestHTTP.HTTPConnection:HandleCallback() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPConnection.cs:594)
    BestHTTP.HTTPManager:OnUpdate() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPManager.cs:358)
    BestHTTP.HTTPUpdateDelegator:Update() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPUpdateDelegator.cs:49)
     
  28. desyashasyi

    desyashasyi

    Joined:
    Nov 22, 2012
    Posts:
    73
    Ah.. it stupid, I send data from unity, because i want to see the result, i refresh the php page, so the parameter should be gone. Now, what is the solution if I want save the incoming data to database (mySQL)? is there any example how to save the data? Is the leaderboard example is suitable?


    But in leaderboard example I did not see how to write data to the mySql database. Could you post an example how to achieve it?
     
    Last edited: Feb 23, 2015
  29. desyashasyi

    desyashasyi

    Joined:
    Nov 22, 2012
    Posts:
    73
    OK, I solved my problem. Sorry for spamming this thread :).
     
  30. Zaddo67

    Zaddo67

    Joined:
    Aug 14, 2012
    Posts:
    489
    Oops, I missed that. :oops:

    Thx.
     
  31. baneand

    baneand

    Joined:
    Dec 3, 2013
    Posts:
    8
    Hi,

    Do you have any examples how to connect to websocket with post method? I tried looking at your code but I didn't want to change it until I ask for an examle. Default connecting in WebSocket.cs class is with get method, and I am guessing it is being done with InternalRequest object.

    Thanks.
     
  32. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    You are right about InternalRequest, but i don't have an example and i didn't tried to connect with post either.
    However, you can add a HTTPMethodes.Post to the InternalRequest's constructor changing it to a post request:
    Code (CSharp):
    1. InternalRequest = new HTTPRequest(uri, HTTPMethods.Post, (req, resp) => {
    But i think you have to change the server side too to be able to upgrade the connection to WebSocket. The plugin doesn't checks what request type used, so it should work with post too just fine.
     
  33. baneand

    baneand

    Joined:
    Dec 3, 2013
    Posts:
    8
    Thanks for fast reply! Yes server side is also changed but I need to post few parameters with initial request. Using get method I passed them with url, here I suppose to pass them in json form. Can you tell me where should I put that along with InternalRequest?
     
  34. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    I would change the WebSocket's constructor:
    Code (CSharp):
    1. public WebSocket(Uri uri, string origin, string protocol = "", System.Collections.Generic.Dictionary<string, string> postParams = null, byte[] postData = null)
    2. {
    3.     // ...
    4.  
    5.     InternalRequest = new HTTPRequest(uri, HTTPMethods.Post, (req, resp) => {
    6.             if ((resp == null || req.Exception != null) && OnError != null || (resp != null && resp.StatusCode != 101))
    7.                 OnError(this, req.Exception);
    8.         });
    9.  
    10.     if (postParams != null)
    11.         foreach (var param in postParams)
    12.             InternalRequest.AddField(param.Key, param.Value);
    13.  
    14.     if (postData != null)
    15.         InternalRequest.RawData = postData;
    16.  
    17.     // ...
    18.  
    Don't know how you want to send your json data, so there are two options to choose from:

    Code (CSharp):
    1.  
    2. var formFields = new Dictionary<string, string>();
    3. formFields.Add("jsonData", "['some json data']");
    4. webSocket = new WebSocket(new Uri(address), string.Empty, string.Empty, formFields);
    5.  
    Code (CSharp):
    1.  
    2. byte[] formData = System.Text.Encoding.UTF8.GetBytes("['some json data']");
    3. webSocket = new WebSocket(new Uri(address), string.Empty, string.Empty, null, formData);
    4.  
     
  35. julianr

    julianr

    Joined:
    Jun 5, 2014
    Posts:
    1,212
    Hi, after installing BestHTTP Basic on a fresh project, moved Plugins to the Assets folder, I get the following message:
    Assets/Best HTTP (Basic)/Examples/LargeFileDownloadSample.cs(34,37): error CS0122: `BestHTTP.HTTPResponse.MinBufferSize' is inaccessible due to its protection level
    Seems like its not picking up the DLL, maybe.. as if I remove this file, it errors on all of the other examples. Using Unity 4.6.2f

    I also made sure I deleted the previous version in case of any conflicts.
     
    Last edited: Feb 25, 2015
  36. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    For a quick fix you can delete the /Best HTTP (Basic)/Examples folder.
    Will include a complete fix in today's update.
     
    julianr likes this.
  37. fingersbleeding

    fingersbleeding

    Joined:
    Jun 10, 2013
    Posts:
    24
    Hi,
    Our team (Flyclops) has been using BestHTTP in the wild for some time now to handle our Android API requests. We've found an issue that I'd like to share and maybe get some feedback on what the larger issue might be.

    The larger issue:
    We make a request to our API, the API will do it's thing, and then returns a JSON packet to our client. We log the outgoing message in the API and it shows a fully structured JSON response. The client triggers the response handler with no data, as if the API didn't send anything back to the client.

    The smaller issue:
    In HTTPResponse, on line 176:
    if (!baseRequest.DisableRetry && string.IsNullOrEmpty(versionStr))
    return false;

    On this line, you've parsed for versionStr, and test for it's existence, but that's tied to the baseRequest.DisableRetry property and only fails if DisableRetry is set to false.

    On the next few lines:
    string[] versions = versionStr.Split(newchar[] { '/', '.' });
    this.VersionMajor = int.Parse(versions[1]);
    this.VersionMinor = int.Parse(versions[2]);

    If versionStr is null, as it is in our case where the client fires a callback with no data received from the API, you will get an IndexOutOfRange error for the attempt to pull version[1].

    We've added an additional line on 178:
    if(string.IsNullOrEmpty(versionStr)) return false;

    If this sounds right, could you include that fix into the BestHTTP source with a future release?

    If you have any suggestions on why our callbacks might fire with blank datasets, we'd love that input, too.

    Cheers,
    Jason
     
  38. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Hi Jason.

    Seen this error only when the server closes the tcp connection while the client expects data from it after sent a request. DisableRetry is for there to check this case and fail silently to resend the request (and reconnect to the server). But it's disabled for POST requests as these usually have some sideeffect on serverside so it's not considered safe to resend it to the server(and risk duplicated items in an sql database for example). For this case, it will fail hard and produce an IndexOutOfRange exception on purpose. However now I see it as a non-very-informative solution, it would be better to throw an exception with a proper error message...

    But it's just half of the whole story.
    Why the tcp connection closed by the server? It's because the connection pooling mechanism of the plugin. The plugin will send a Keep-Alive header to the server and will not close the tcp connection for a specified time(HTTPManager.MaxConnectionIdleTime). The server has its timer too, and it's usually different from the one on the client, so in some cases the client will send a request when the server closes the tcp connection... When this happen, the client will try to correct by resending the request, as i already mentioned it's disabled for POST requests.

    Solutions?
    -The timer on the client can be changed easily by changing the HTTPManager.MaxConnectionIdleTime to a lower value. The default is 30 secs. I would recommend 15-20 secs for a first try.
    -Keep-Alive (connection pooling) mechanism can be disabled per-request(HTTPRequest's IsKeepAlive) and globally(HTTPManager.KeepAliveDefaultValue) too.

    The answer for this question can be an interesting reading too.
     
  39. ccklokwerks

    ccklokwerks

    Joined:
    Oct 21, 2014
    Posts:
    62
    Hey,

    First, I want to say that I've been using BestHTTP since I started working on this project and am very happy with it.

    I've received a request from above to prioritize downloading some assets over others. Do you have any plans to add priority to HTTPRequests and use that to determine what gets sent first from the queue? Otherwise I guess I'll write my own intermediate layer, but callbacks are going to become a pain, because I'll need HTTPManager to call back to my intermediate layer which will then call back to the actual requester.

    In other words, I'd like to request being able to set a priority on requests. ;-)
     
  40. codeStrider

    codeStrider

    Joined:
    Mar 24, 2014
    Posts:
    4
    Hi There,

    I just bought the pro version of your plugin, but was having an issue compiling for ios using Unity 5. The above answer was the fix I needed to get it working, but the additional ".NET 2.0" overhead puts our application over 100mb and increases our build time drastically.

    Is there a way to use your plugin with the ".NET 2.0 Subset" instead?
     
  41. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    No, unfortunately. But as i read in the 4.6.x il2cpp forum thread they are working on lowering build size very hard.
     
  42. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Looks like it can be done by adding two lines to the plugin. One for the Priority property, and one for sorting the 'queue'. I will do some test tomorrow, and will write you in private how you can download a test version.
     
    ccklokwerks likes this.
  43. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Version 1.7.4 released yesterday, it can be downloaded from the Asset Store.

    This release contains two new features, UploadStream and OnUploadProgress callback:
    Code (CSharp):
    1. var request = new HTTPRequest(new Uri("http://httpbin.org/post"), HTTPMethods.Post, (req, resp) => {...});
    2.  
    3. request.UploadStream = new FileStream("AssetBundle.unity3d", FileMode.Open);
    4. request.OnUploadProgress = (req, up, length) => Debug.Log("Uploaded: " + up.ToString("N0") + " / " + length.ToString("N0"));
    5.    
    6. request.Send();
    Changelog of v1.7.4:
    • [New Feature] New UploadStream property in the HTTPRequest class
    • [New Feature] New OnUploadProgress callback in the HTTPRequest class
    • [Improvement] Switched from System.Action usage to properly named delegates
    • [Improvement] Removed some GC allocs
     
  44. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Tested the plugin with Unity 5 Personal Edition, and it's working fine. Finally a free version that contains the .net sockets. So with Unity 5, don't need a Professional version or another plugin!
     
    julianr likes this.
  45. blueteak

    blueteak

    Joined:
    Feb 19, 2013
    Posts:
    140
    Using Unity 5 iOS (Professional, though I think it doesn't matter) getting the following issue building for iOS:

    Cross compilation job BestHTTP.dll failed.
    UnityEngine.UnityException: Failed AOT cross compiler: /Applications/Unity/Unity.app/Contents/PlaybackEngines/iossupport/Tools/OSX/mono-xcompiler-wrapper.sh --aot=full,asmonly,nodebug,static,outfile="BestHTTP.dll.s" "BestHTTP.dll" current dir : /Users/username/Desktop/Unity Projects/AppName/Temp/StagingArea/Data/Managed
    result file exists: True. Timed out: False
     
  46. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    This error is only affects the Basic version of the plugin, and a fix is uploaded to the Asset Store but doesn't released yet. Sent a download link in private where you can download the update.
     
  47. amansilla

    amansilla

    Joined:
    Mar 4, 2015
    Posts:
    2
    I have a problem with the Plugin in the unity 5 version. After import to unity, the program throw this error:

    Unhandled Exception: System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.

    at (wrapper managed-to-native) System.Reflection.Assembly:GetTypes (bool)

    at System.Reflection.Assembly.GetTypes () [0x00000] in <filename unknown>:0

    at Mono.CSharp.RootNamespace.ComputeNamespaces (System.Reflection.Assembly assembly, System.Type extensionType) [0x00000] in <filename unknown>:0

    at Mono.CSharp.RootNamespace.ComputeNamespace (Mono.CSharp.CompilerContext ctx, System.Type extensionType) [0x00000] in <filename unknown>:0

    at Mono.CSharp.GlobalRootNamespace.ComputeNamespaces (Mono.CSharp.CompilerContext ctx) [0x00000] in <filename unknown>:0

    at Mono.CSharp.Driver.LoadReferences () [0x00000] in <filename unknown>:0

    at Mono.CSharp.Driver.Compile () [0x00000] in <filename unknown>:0

    at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0
     
  48. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Please make sure that the /Plugin/ folder from the /Best HTTP (Pro|Basic)/ folder is moved to the root /Assets/ folder.
     
  49. amansilla

    amansilla

    Joined:
    Mar 4, 2015
    Posts:
    2
    Thankyou for your reply. The problem was resolved, but I have a new issue. Is the plugin webgl compatible?
    I am trying to compile in webgl but I have this error:
    missing function: pthread_create.



    Invoking error handler due to
    uncaught exception: abort() at jsStackTrace@http://localhost/unitydemo2/Release/unitydemo2.js:992:13
    stackTrace@http://localhost/unitydemo2/Release/unitydemo2.js:1009:22
    abort@http://localhost/unitydemo2/Release/unitydemo2.js:4339138:25
    _pthread_create@http://localhost/unitydemo2/Release/unitydemo2.js:10478:59
    __ZN6il2cpp2os10ThreadImpl3RunEPFvPvES2_ [il2cpp::eek:s::ThreadImpl::Run(undefined?F?*, void, void*)]@http://localhost/unitydemo2/Release/unitydemo2.js:70303:9
    __ZN6il2cpp2os6Thread3RunEPFvPvES2_ [il2cpp::eek:s::Thread::Run(undefined?F?*, void, void*)]@http://localhost/unitydemo2/Release/unitydemo2.js:62876:8
    __ZN6il2cpp6icalls8mscorlib6System9Threading6Thread15Thread_internalEP12Il2CppThreadP14Il2CppDelegate [il2cpp::icalls::mscorlib::System::Threading::Thread::Thread_internal(Il2CppDelegate?**)]@http://localhost/unitydemo2/Release/unitydemo2.js:57572:3
    __Z6m33286P4t226P3t47P10MethodInfo [m33286(MethodInfo?***)]@http://localhost/unitydemo2/Release/unitydemo2.js:3084883:8
    __Z5m1974P4t226P10MethodInfo [m1974(MethodInfo?**)]@http://localhost/unitydemo2/Release/unitydemo2.js:3085308:9
    __Z4m563P4t104P3t10P10MethodInfo [m563(MethodInfo?***)]@http://localhost/unitydemo2/Release/unitydemo2.js:2489769:3
    __Z4m616P2t5P3t10P10MethodInfo [m616(MethodInfo?***)]@http://localhost/unitydemo2/Release/unitydemo2.js:2493629:2
    __Z4m614P2t5P3t10P10MethodInfo [m614(MethodInfo?***)]@http://localhost/unitydemo2/Release/unitydemo2.js:2493280:3
    __Z4m765P3t10P10MethodInfo [m765(MethodInfo?**)]@http://localhost/unitydemo2/Release/unitydemo2.js:2497947:8
    __Z5m1771P4t308P10MethodInfo [m1771(MethodInfo?**)]@http://localhost/unitydemo2/Release/unitydemo2.js:2543391:3
    __Z19RuntimeInvoker_t155P10MethodInfoPvPS1_ [RuntimeInvoker_t155?1(void**, undefined?S?*)]@http://localhost/unitydemo2/Release/unitydemo2.js:3981296:2
    __ZN6il2cpp2vm7Runtime6InvokeEP10MethodInfoPvPS4_PP12Il2CppObject [il2cpp::vm::Runtime::Invoke?4(void**, undefined?S?*)]@http://localhost/unitydemo2/Release/unitydemo2.js:96122:8
    _il2cpp_runtime_invoke@http://localhost/unitydemo2/Release/unitydemo2.js:29971:8
    __Z20il2cpp_invoke_method21ScriptingMethodIl2CppP15ScriptingObjectP18ScriptingArgumentsPP18ScriptingExceptionb [il2cpp_invoke_method?2()]@http://localhost/unitydemo2/Release/unitydemo2.js:1251063:9
    __ZN19ScriptingInvocation6InvokeEPP18ScriptingException [ScriptingInvocation::Invoke(ScriptingException?**)]@http://localhost/unitydemo2/Release/unitydemo2.js:1518931:9
    __ZN13MonoBehaviour30InvokeMethodOrCoroutineCheckedE21ScriptingMethodIl2CppP15ScriptingObjectPP18ScriptingException [MonoBehaviour::InvokeMethodOrCoroutineChecked?2()]@http://localhost/unitydemo2/Release/unitydemo2.js:1510395:10
    __ZN13MonoBehaviour30InvokeMethodOrCoroutineCheckedE21ScriptingMethodIl2CppP15ScriptingObject [MonoBehaviour::InvokeMethodOrCoroutineChecked?2()]@http://localhost/unitydemo2/Release/unitydemo2.js:1511011:9
    __ZN13MonoBehaviour16DelayedStartCallEP6ObjectPv [MonoBehaviour::DelayedStartCall(void**)]@http://localhost/unitydemo2/Release/unitydemo2.js:1509275:3
    __ZN18DelayedCallManager6UpdateEi [DelayedCallManager::Update(int)]@http://localhost/unitydemo2/Release/unitydemo2.js:1214117:11
    __Z10PlayerLoopbbP10IHookEvent [PlayerLoop(bool, bool, IHookEvent?*)]@http://localhost/unitydemo2/Release/unitydemo2.js:1416118:4
    __ZL8mainloopv [mainloop()]@http://localhost/unitydemo2/Release/unitydemo2.js:2419650:2
    dynCall_v@http://localhost/unitydemo2/Release/unitydemo2.js:4333194:7
    Runtime.dynCall@http://localhost/unitydemo2/Release/unitydemo2.js:277:14
    Browser_mainLoop_runner/<@http://localhost/unitydemo2/Release/unitydemo2.js:10090:13
    Browser.mainLoop.runIter@http://localhost/unitydemo2/Release/unitydemo2.js:6144:13
    Browser_mainLoop_runner@http://localhost/unitydemo2/Release/unitydemo2.js:10086:9

    If this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.
     
  50. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,664
    Unfortunately I can't support it, as it doesn't support Sockets. I'm looking for a way how can i support at least some of the base features, but i don't had the time yet(IL2CPP caused too much trouble).
     
    Last edited: Mar 5, 2015