Code Monkey home page Code Monkey logo

unityhttp's Introduction

Attribution

Based on Simon Wittber's UnityWeb code (http://code.google.com/p/unityweb/).

LICENSE

UnityHTTP falls under the GPL due to its basis on Simon Wittber's UnityWeb code, which is licensed under the GPL.

You should be aware of this license and determine if it is acceptable for your project.

About

This is a TcpClient-based HTTP library for use in Unity. It should work in both the standalone player and in the web player.

It also has convenience methods for working with JSON.

Examples

IEnumerator example:

public IEnumerator SomeRoutine() {
    HTTP.Request someRequest = new HTTP.Request( "get", "http://someurl.com/somewhere" );
    someRequest.Send();

    while( !someRequest.isDone )
    {
        yield return null;
    }

    // parse some JSON, for example:
    JSONObject thing = new JSONObject( request.response.Text );
}

Closure-style (does not need to be in a coroutine):

HTTP.Request someRequest = new HTTP.Request( "get", "http://someurl.com/somewhere" );
someRequest.Send( ( request ) => {
    // parse some JSON, for example:
    JSONObject thing = new JSONObject( request.response.Text );
});

Post request using form data:

WWWForm form = new WWWForm();
form.AddField( "something", "yo" );
form.AddField( "otherthing", "hey" );

HTTP.Request someRequest = new HTTP.Request( "post", "http://someurl.com/some/post/handler", form );
someRequest.Send( ( request ) => {
    // parse some JSON, for example:
    bool result = false;
    Hashtable thing = (Hashtable)JSON.JsonDecode( request.response.Text, ref result );
    if ( !result )
    {
        Debug.LogWarning( "Could not parse JSON response!" );
        return;
    }
});

Post request using JSON:

Hashtable data = new Hashtable();
data.Add( "something", "hey!" );
data.Add( "otherthing", "YO!!!!" );

// When you pass a Hashtable as the third argument, we assume you want it send as JSON-encoded
// data.  We'll encode it to JSON for you and set the Content-Type header to application/json
HTTP.Request theRequest = new HTTP.Request( "post", "http://someurl.com/a/json/post/handler", data );
theRequest.Send( ( request ) => {

    // we provide Object and Array convenience methods that attempt to parse the response as JSON
    // if the response cannot be parsed, we will return null
    // note that if you want to send json that isn't either an object ({...}) or an array ([...])
    // that you should use JSON.JsonDecode directly on the response.Text, Object and Array are
    // only provided for convenience
    Hashtable result = request.response.Object;
    if ( result == null )
    {
        Debug.LogWarning( "Could not parse JSON response!" );
        return;
    }
  
});

If you want to make a request while not in Play Mode (e. g. from a custom Editor menu command or wizard), you must use the Request synchronously, since Unity's main update loop is not running. The call will block until the response is available.

Hashtable data = new Hashtable();
data.Add( "something", "hey!" );
data.Add( "otherthing", "YO!!!!" );

HTTP.Request theRequest = new HTTP.Request("post", "http://someurl.com/a/json/post/handler", data );
theRequest.synchronous = true;
theRequest.Send((request) => {
	EditorUtility.DisplayDialog("Request was posted.", request.response.Text, "Ok");
});

unityhttp's People

Contributors

adrianrudnik avatar alejandrohuerta avatar andyburke avatar andzdroid avatar codemonkeywang avatar crappygraphix avatar darl2ng avatar ddaws avatar denizpiri avatar godefroy avatar jkb0o avatar kronenthaler avatar paynechu avatar rmalecki avatar simonwittber avatar yongkangchen avatar zlumer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unityhttp's Issues

Cross-domain policy / webplayer

Hope this isn't "stupid question" territory, but here goes.

I'm trying to use the https://www.leaderboards.io webapi from Unity using UnityHTTP. It's working fine in desktop builds. In webplayer builds, the following exception occurs:

SecurityException: Unable to connect, as no valid crossdomain policy was found

I'm making a PUT request asynchronously like so:

HTTP.Request theRequest = new HTTP.Request("put", "https://api.leaderboards.io/leaderboard/063f5e89611ff77b/score", data);
    theRequest.Send((request) =>
    {
                  Debug.LogError(request.exception);
...

A crossdomain.xml file exists at https://api.leaderboards.io/crossdomain.xml. I get the policy not found exception when running in the editor (webplayer platform) and also with the webplayer (hosted locally on IIS and also tried on Azure).

I tried doing a Fiddler debug, but the request doesn't show at all (in either the desktop build or webplayer - not sure if it should!)

Unity version 5.1.2f1, by the way.

Any ideas?

HTTP Request with WWWForm fails with error

When using a WWWForm in a request, it fails when parsing the headers. This is because it is looking for a KeyValuePair in a hashtable:

foreach ( KeyValuePair<string,string> pair in form.headers )
{
this.AddHeader(pair.Key,pair.Value);
}

Can be fixed by using DictionaryEntry instead:

foreach ( DictionaryEntry entry in form.headers )
{
this.AddHeader(entry.Key.ToString(), entry.Value.ToString());
}

UnityHTTP and Proxy

The Request class, after send(), does not use my proxy configuration set in Windows. Using System.Net.WebClient allows me to get my web page perfectly, but when using Request class, it returns a HTML fire returned by my proxy server at work saying access denied (and it is indeed denied if you don't set proxy in Windows). I can access the page normally in any browser.

CookieJar.cs parse "expires" time exception

i get the time string like this:"expires=Thu, 21-Mar-2013 07:31:55 GMT"

case "expires":
this.expirationDate = DateTime.Parse( match.Groups[ 2 ].Value );
break;

throw an System.FormatException:String was not recognized as a valid DateTime

anybody else has the same problem?

value = value.Trim (); throws NullReferenceException

Full exception

NullReferenceException: Object reference not set to an instance of an object UnityHTTP.Request.SetHeader (System.String name, System.String value) (at Assets/Third Party/UnityHTTP/src/Request.cs:153) Login+<LoginRequest>c__IteratorF.MoveNext () (at Assets/scripts/Login.cs:270) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17) UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator) <LoginRetrieve>c__IteratorD:MoveNext() (at Assets/scripts/Login.cs:197)

I'm willing to accept the fact that this may be a problem in my own code, but I thought I would post an issue here in case someone can verify for me if this is caused by my code or UnityHTTP. I last had this working in 2014 and some major changes have been made to both the Habitica API, that I'm trying to access, and to UnityHTTP since then.

iOS support?

Will there be any iOS support? Right now it fails compiling.

Cross compilation job Ionic.Zlib.dll failed.
UnityEngine.UnityException: Failed AOT cross compiler: /Applications/Unity/Unity.app/Contents/PlaybackEngines/iOSSupport/Tools/OSX/mono-xcompiler --aot=full,asmonly,nodebug,static,outfile="Ionic.Zlib.dll.s" "Ionic.Zlib.dll"  current dir : /Users/hex/Webplayer-Socket NetEase/Temp/StagingArea/Data/Managed
 Env: DISPLAY = '/tmp/launch-RlDnwf/org.macosforge.xquartz:0'
Apple_PubSub_Socket_Render = '/tmp/launch-uUCwHn/Render'
LOGNAME = 'hex'
__CHECKFIX1436934 = '1'
MONO_PATH = '/Users/hex/Webplayer-Socket NetEase/Temp/StagingArea/Data/Managed'
ENABLE_CROSSDOMAIN_LOGGING = '1'
TMPDIR = '/var/folders/ln/tky5wdmj0535jh18srs_sljr0000gn/T/'
USER = 'hex'
SSH_AUTH_SOCK = '/tmp/launch-7c0Nfz/Listeners'
GC_DONT_GC = 'yes please'
Error building Player: UnityException: Cross compilation failed.

HTTPS Fails on Certain Servers

Hey Andy,

Thanks for all the great work first off -- it's been wonderful having a replacement for the oh-so-sad WWW class.

I've run into some issues in working with SSL connections. For example:

Site: https://www.domain.com/
With Unity's WWW: works fine.
With UnityHTTP: Exception: The authentication or decryption has failed. (No trace or additional information in console.)

When you check https://www.domain.com/, it works in Chrome, passes Digicert's SSL checker, and passes SSLLabs SSL checker. I'm stumped, and would really like to not switch back to Unity's WWW class.

Any thoughts or ideas? Google'ing around seems to indicate missing CA certs, and importing them with mozroots, but that didn't solve the problem. Any thoughts?

Thanks!

Cheers,
Austin

doesn't work on Unity Web player.

Hey,
I looked at ur code and it looks really nice and working perfectly in Unity Stanalone applicaiton. When I try to call from Webplayer environment, request always return null even inside editor. Can someone give me example working code for Unity webplayer?

JSON body in Form post

Is there a way to make this request using your library ?
curl -k -F "request={'timezone':'America/New_York', 'lang':'en'};type=application/json" -F "[email protected];type=audio/wav" -H "Authorization: Bearer YOUR_ACCESS_TOKEN" -H "ocp-apim-subscription-key: YOUR_SUBSCRIPTION_KEY" https://api.api.ai/v1/query

As you can see its a form with JSON body and a binary file. But I just can't understand if your library can do this.

Cannot integrate UnityHTTP in Version 5.0.1f1

I get compile errors when trying to integrate UnityHTTP in my project.

Steps:
cd Library/Plugins

git clone [email protected]:andyburke/UnityHTTP.git

I then get the error

Assets/Plugins/UnityHTTP/src/Request.cs(80,13): error CS0030: Cannot convert type `System.Collections.Generic.KeyValuePair<string,string>' to `System.Collections.DictionaryEntry'

What is wrong? It Unity 5 not supported? Should the code reside in a different place? Is there a different import process I should use?

Speeding Up UnityHTTP

I've been using UnityHTTP to get Unity to talk to a Philips Hue bulb and so far it has been working ok, but with a lot of lag (1+ second per request).

Unfortunately, I am fairly new to Unity and have almost no network coding experience. I have been experimenting with removing the code that deals with responses (I think) from request.cs:

response = new Response ();
response.request = this;
state = RequestState.Reading;
response.ReadFromStream(ostream);

and

switch (response.status) {
case 307:
case 302:
case 301:
uri = new Uri (response.GetHeader ("Location"));
continue;
default:
retry = maximumRetryCount;
break;
}

And also changing MaximumRetryCount - however if I use a number below 2 here the message fails to work at all.

I'm most interested in the light changing immediately, and not interested in retrying or any responses the light returns. Do you have any tips as to how I might speed this up?

Single string value PUT/POST

Is there any way to make a "PUT" request with a single string value? I'm using this library to make REST calls to Firebase -- their "PUT" allows (and often requires) writing to an "end node" with a single value (so as not to override data) -- I basically want to do:

curl -X PUT -d '"June 23, 1912"' \
  'https://docs-examples.firebaseio.com/rest/saving-data/fireblog/users/alanisawesome/birthday.json'

As is described in this documentation. (look at the "PUT" section)

I basically want to be able to do something like:

UnityHTTP.Request req = new UnityHTTP.Request ("put",
            getDBUrl("/users/" + uid + "/assessments/" + aid), true);

Notice the bool instead of a HashTable (this could just be a string)

How set timeout

Is there any timeout support, like below? That would be very convenience.

HTTP.Request someRequest = new HTTP.Request("get", uri);
someRequest.SetTime(5);
someRequest.Send((request) => {
    if (request.response != null)
        // handle response here 
    else {
        if (request.exception is TimeOutException) // Timeout!
        else // other exception.
    }
})

Clarify license?

What's the license on UnityHTTP? If it's GPL then as I'm guessing then it's a rather restrictive license for a library as it forces users of it to publish the source code for their game as well.

GPL is dangerous

By using this library, projects theoretically MUST publish their source code when they distribute their application. As most games are closed-source, this makes this library unusable. It also means they should not be published on the iOS app store.

Brand Logo

Hello.

I am creating a provider for UnityHTTP for our asset Web API Kit on the Unity asset store.
This will allow users to plug and play with UnityHTTP and our RESTful implementations.
I would like to include UnityHTTP's logo on the 'UnityHTTP Provider' free asset (no code is shared from your repo).

Do you have a logo?

http://unity3dassets.com/product/web-api-kit-unityhttp-provider/

/chris

how to set up unityHTTP?

Hi! I trying to figure out how to set up this UnityHTTP in my project,
In can't understand Readme file.

I just copy the source code into the Assets folder.. that is ok?

Somebody can give me a clue?

Thanks!!

What license does this use?

What license does this use?

Also, on an unrelated note, sha-256 certs work with unity now , because I made a pull request and they merged it. It wasn't in the release notes, which is why I'm mentioning it here.

Requires Android/iOS Pro

Tremendously helpful library, unfortunately using their TcpClient library means you'll need to spend $3000 on Pro licenses to use them mobile...

Object was used after being disposed.

I was using uniweb, and I thought I would try unityhttp. I changed what I thought needed to be changed and then I received the following error.

System.ObjectDisposedException: The object was used after being disposed.
at System.IO.MemoryStream.CheckIfClosedThrowDisposed () [0x0000b] in /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.IO/MemoryStream.cs:135
at System.IO.MemoryStream.SetLength (Int64 value) [0x00023] in /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.IO/MemoryStream.cs:339
at HTTP.Response.ReadFromStream (System.IO.Stream inputStream) [0x0023e] in G:\workfiles\unity projects\HME\Assets\UnityHTTP\Response.cs:221
at HTTP.Request.GetResponse () [0x0012d] in G:\workfiles\unity projects\HME\Assets\UnityHTTP\Request.cs:180
UnityEngine.Debug:LogError(Object)
c__Iterator7:MoveNext() (at Assets/scripts/Login.cs:268)

Exception on HTTPS request

Getting exception on HTTPS request : The authentication or decryption has failed.
image

is it possible to fix this or is there any workaround ?

REST API extension

We've created our REST SDK on the shoulders of UnityHTTP. It provides API similar to https://github.com/mgonto/restangular, implements path building, error handling, and other useful things. You can find it here: https://github.com/vedi/restifizer-unity3d

For example it allows something like that:

 RestifizerManager.ResourceAt("api/users").
   WithBearerAuth().
   One(userId).
   Patch(parameters, (response) => {
     // response.Resource - at this point you can use the result 
   });

We'd appreciate if you mention it in your README, if it's possible.

Can not request with https

I try to call the api from mobile side and I got this

IOException: BeginWrite failure
System.Net.Sockets.NetworkStream.BeginWrite (System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback callback, System.Object state)
Mono.Security.Protocol.Tls.RecordProtocol.BeginSendRecord (ContentType contentType, System.Byte[] recordData, System.AsyncCallback callback, System.Object state)
Mono.Security.Protocol.Tls.RecordProtocol.SendRecord (ContentType contentType, System.Byte[] recordData)
Mono.Security.Protocol.Tls.RecordProtocol.SendAlert (Mono.Security.Protocol.Tls.Alert alert)
Mono.Security.Protocol.Tls.RecordProtocol.SendAlert (AlertDescription description)
Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
UnityEngine.Debug:LogException(Exception)
UnityHTTP.Request:GetResponse() (at Assets/Plugins/UnityHTTP/src/Request.cs:197)
UnityHTTP.Request:m__0(Object) (at Assets/Plugins/UnityHTTP/src/Request.cs:336)

How to solve this problem? Thank you.
Unity 5.4

"Unhandled Exception, aborting request" while switching off wifi

Unhandled Exception, aborting request.

SocketException: No such host is known
System.Net.Dns.hostent_to_IPHostEntry (System.String h_name, System.String[] h_aliases, System.String[] h_addrlist)
System.Net.Dns.GetHostByName (System.String hostName)
System.Net.Dns.GetHostEntry (System.String hostNameOrAddress)
System.Net.Dns.GetHostAddresses (System.String hostNameOrAddress)
System.Net.Sockets.TcpClient.Connect (System.String hostname, Int32 port)

Add tests using Nunit

The name is pretty self explanatory. I am considering creating another project with a folder, test. I will then add a Solution file to open them both up easily.

I don't plan to add test coverage for things all right away, though was hoping to add tests as the need for them arose. I figured setting up the scaffolding will make it easier for others to contribute to this.

Enumerate HTTP Method types

I would like to make this available because I don't trust my self not spell the method type wrong by accident. I intend to implement by creating an enumeration of the method types and adding a constructor that accepts the enum as a param and fallback on the string based constructor.

Support for multipart request

Does this library support using multipart request & file streams ? for eg. uploading a file.
Since converting the huge file into bytes[] in memory might be impossible.

If not, is there any suggested work around. Also this might be a good feature to add to this http client.

Exception is thrown in JSON parser ParseString (char[] json, ref int index, ref bool success)

The function in lib/JSON.cs:193 protected static string ParseString (char[] json, ref int index, ref bool success)
throws an exception "The argument must not be in surrogate pair range" in lib/JSON.cs:244 s.Append (Char.ConvertFromUtf32 ((int)codePoint)); that is not handled by (tested on instagram API, media/popular endpoint). If you assume JSON API return status code via bool argument, this exception must be handled.

I've muted it with

try{
  // convert the integer codepoint to a unicode char and add to string
  s.Append (Char.ConvertFromUtf32 ((int)codePoint));
}catch(Exception e){
  s.Append ( "" );
}

it works, but i'm not sure if it is correct logic.

Error when running in a thread

Hi,

When I call a UnityHTTP method from a thread, I get this error:

get_unityVersion can only be called from the main thread.

To fix this and thus allow to use UnityHTTP in a thread, you can remove Application.unityVersion by replacing this line:

SetHeader( "User-Agent", "UnityWeb/1.0 (Unity " + Application.unityVersion + "; " + SystemInfo.operatingSystem + ")" );

by this line:

SetHeader( "User-Agent", "UnityWeb/1.0 (Unity; " + SystemInfo.operatingSystem + ")" );

How to import this into a Unity 5 project?

Hello! I have been all day trying to figure out how to import this project into a Unity 5 project but couldn't find the way.

I've tried to add as reference, but the project is not displayed. Also as a side project, but then and for some reason using can't find the classes (maybe it fails to compile because missing dependencies?).

Is there a guide for Unity 4? That will probably be the same thing.

PS: I hope you tag this a question only, not an actual bug :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.