Giter Site home page Giter Site logo

proyecto26 / restclient Goto Github PK

View Code? Open in Web Editor NEW
1.2K 36.0 174.0 48.68 MB

🦄 A Promise based REST and HTTP client for Unity 🎮

Home Page: https://assetstore.unity.com/packages/slug/102501

License: MIT License

C# 100.00%
unity promises http http-client rest-client rest unity-scripts web-services json web-request

restclient's Introduction

Made with Unity License Maintenance Tidelift Subscription Build Status Twitter Follow

RestClient for Unity 🤘

RestClient for Unity

Proyecto26.RestClient logo

This HTTP/REST Client is based on Promises to avoid the Callback Hell ☠️ and the Pyramid of doom 💩 working with Coroutines in Unity 🎮, example:

var api = "https://jsonplaceholder.typicode.com";
RestClient.GetArray<Post>(api + "/posts", (err, res) => {
  RestClient.GetArray<Todo>(api + "/todos", (errTodos, resTodos) => {
    RestClient.GetArray<User>(api + "/users", (errUsers, resUsers) => {
      //Missing validations to catch errors!
    });
  });
});

But working with Promises we can improve our code, yay! 👏

RestClient.GetArray<Post>(api + "/posts").Then(response => {
  EditorUtility.DisplayDialog ("Success", JsonHelper.ArrayToJson<Post>(response, true), "Ok");
  return RestClient.GetArray<Todo>(api + "/todos");
}).Then(response => {
  EditorUtility.DisplayDialog ("Success", JsonHelper.ArrayToJson<Todo>(response, true), "Ok");
  return RestClient.GetArray<User>(api + "/users");
}).Then(response => {
  EditorUtility.DisplayDialog ("Success", JsonHelper.ArrayToJson<User>(response, true), "Ok");
}).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok"));

Features 🎮

  • Works out of the box 🎉
  • Make HTTP requests from Unity
  • Supports HTTPS/SSL
  • Built on top of UnityWebRequest system
  • Transform request and response data (JSON serialization with JsonUtility or other tools)
  • Automatic transforms for JSON Arrays.
  • Supports default HTTP Methods (GET, POST, PUT, DELETE, HEAD, PATCH)
  • Generic REQUEST method to create any http request
  • Based on Promises for a better asynchronous programming. Learn about Promises here!
  • Utility to work during scene transition
  • Handle HTTP exceptions and retry requests easily
  • Open Source 🦄

Supported platforms 📱 🖥

The UnityWebRequest system supports most Unity platforms:

  • All versions of the Editor and Standalone players
  • WebGL
  • Mobile platforms: iOS, Android
  • Universal Windows Platform
  • PS4 and PSVita
  • XboxOne
  • HoloLens
  • Nintendo Switch

Demo ⏯

Do you want to see this beautiful package in action? Download the demo here

Unity configuration Demo

Installation 👨‍💻

Unity package

Download and install the .unitypackage file of the latest release published here.

UPM package

Make sure you had installed C# Promise package or at least have it in your openupm scope registry. Then install RestClient package using this URL from Package Manager: https://github.com/proyecto26/RestClient.git#upm

NuGet package

Other option is download this package from NuGet with Visual Studio or using the nuget-cli, a NuGet.config file is required at the root of your Unity Project, for example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value="./Assets/Packages" />
  </config>
</configuration>

The package to search for is Proyecto26.RestClient.

Getting Started 📚

The default methods (GET, POST, PUT, DELETE, HEAD) are:

RestClient.Get("https://jsonplaceholder.typicode.com/posts/1").Then(response => {
  EditorUtility.DisplayDialog("Response", response.Text, "Ok");
});
RestClient.Post("https://jsonplaceholder.typicode.com/posts", newPost).Then(response => {
  EditorUtility.DisplayDialog("Status", response.StatusCode.ToString(), "Ok");
});
RestClient.Put("https://jsonplaceholder.typicode.com/posts/1", updatedPost).Then(response => {
  EditorUtility.DisplayDialog("Status", response.StatusCode.ToString(), "Ok");
});
RestClient.Delete("https://jsonplaceholder.typicode.com/posts/1").Then(response => {
  EditorUtility.DisplayDialog("Status", response.StatusCode.ToString(), "Ok");
});
RestClient.Head("https://jsonplaceholder.typicode.com/posts").Then(response => {
  EditorUtility.DisplayDialog("Status", response.StatusCode.ToString(), "Ok");
});

Handling during scene transition

ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
  //Any API call using RestClient
});

Generic Request Method

And we have a generic method to create any type of request:

RestClient.Request(new RequestHelper { 
  Uri = "https://jsonplaceholder.typicode.com/photos",
  Method = "POST",
  Timeout = 10,
  Params = new Dictionary<string, string> {
    { "param1", "Query string param..." }
  },
  Headers = new Dictionary<string, string> {
    { "Authorization", "Bearer JWT_token..." }
  },
  Body = newPhoto, //Serialize object using JsonUtility by default
  BodyString = SerializeObject(newPhoto), //Use it instead of 'Body' to serialize using other tools
  BodyRaw = CompressToRawData(newPhoto), //Use it instead of 'Body' to send raw data directly
  FormData = new WWWForm(), //Send files, etc with POST requests
  SimpleForm = new Dictionary<string, string> {}, //Content-Type: application/x-www-form-urlencoded
  FormSections = new List<IMultipartFormSection>() {}, //Content-Type: multipart/form-data
  CertificateHandler = new CustomCertificateHandler(), //Create custom certificates
  UploadHandler = new UploadHandlerRaw(bytes), //Send bytes directly if it's required
  DownloadHandler = new DownloadHandlerFile(destPah), //Download large files
  ContentType = "application/json", //JSON is used by default
  Retries = 3, //Number of retries
  RetrySecondsDelay = 2, //Seconds of delay to make a retry
  RetryCallbackOnlyOnNetworkErrors = true, //Invoke RetryCallack only when the retry is provoked by a network error
  RetryCallback = (err, retries) => {}, //See the error before retrying the request
  ProgressCallback = (percent) => {}, //Reports progress of the request from 0 to 1
  EnableDebug = true, //See logs of the requests for debug mode
  IgnoreHttpException = true, //Prevent to catch http exceptions
  ChunkedTransfer = false,
  UseHttpContinue = true,
  RedirectLimit = 32,
  DefaultContentType = false, //Disable JSON content type by default
  ParseResponseBody = false //Don't encode and parse downloaded data as JSON
}).Then(response => {
  //Get resources via downloadHandler to get more control!
  Texture texture = ((DownloadHandlerTexture)response.Request.downloadHandler).texture;
  AudioClip audioClip = ((DownloadHandlerAudioClip)response.Request.downloadHandler).audioClip;
  AssetBundle assetBundle = ((DownloadHandlerAssetBundle)response.Request.downloadHandler).assetBundle;

  EditorUtility.DisplayDialog("Status", response.StatusCode.ToString(), "Ok");
}).Catch(err => {
  var error = err as RequestException;
  EditorUtility.DisplayDialog("Error Response", error.Response, "Ok");
});
  • Example downloading an audio file:
var fileUrl = "https://raw.githubusercontent.com/IonDen/ion.sound/master/sounds/bell_ring.ogg";
var fileType = AudioType.OGGVORBIS;

RestClient.Get(new RequestHelper {
  Uri = fileUrl,
  DownloadHandler = new DownloadHandlerAudioClip(fileUrl, fileType)
}).Then(res => {
  AudioSource audio = GetComponent<AudioSource>();
  audio.clip = ((DownloadHandlerAudioClip)res.Request.downloadHandler).audioClip;
  audio.Play();
}).Catch(err => {
  EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
});

With all the methods we have the possibility to indicate the type of response, in the following example we're going to create a class and the HTTP requests to load JSON data easily:

[Serializable]
public class User
{
  public int id;
  public string name;
  public string username;
  public string email;
  public string phone;
  public string website;
}
  • GET JSON
var usersRoute = "https://jsonplaceholder.typicode.com/users"; 
RestClient.Get<User>(usersRoute + "/1").Then(firstUser => {
  EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(firstUser, true), "Ok");
});
  • GET Array (JsonHelper is an extension to manage arrays)
RestClient.GetArray<User>(usersRoute).Then(allUsers => {
  EditorUtility.DisplayDialog("JSON Array", JsonHelper.ArrayToJsonString<User>(allUsers, true), "Ok");
});

Also we can create different classes for custom responses:

[Serializable]
public class CustomResponse
{
  public int id;
}
  • POST
RestClient.Post<CustomResponse>(usersRoute, newUser).Then(customResponse => {
  EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(customResponse, true), "Ok");
});
  • PUT
RestClient.Put<CustomResponse>(usersRoute + "/1", updatedUser).Then(customResponse => {
  EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(customResponse, true), "Ok");
});

Custom HTTP Headers, Params and Options 💥

HTTP Headers, such as Authorization, can be set in the DefaultRequestHeaders object for all requests

RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ...";

Query string params can be set in the DefaultRequestParams object for all requests

RestClient.DefaultRequestParams["param1"] = "Query string value...";

Also we can add specific options and override default headers and params for a request

var currentRequest = new RequestHelper { 
  Uri = "https://jsonplaceholder.typicode.com/photos",
  Headers = new Dictionary<string, string> {
    { "Authorization", "Other token..." }
  },
  Params = new Dictionary<string, string> {
    { "param1", "Other value..." }
  }
};
RestClient.GetArray<Photo>(currentRequest).Then(response => {
  EditorUtility.DisplayDialog("Header", currentRequest.GetHeader("Authorization"), "Ok");
});

And we can know the status of the request and cancel it!

currentRequest.UploadProgress; //The progress by uploading data to the server
currentRequest.UploadedBytes; //The number of bytes of body data the system has uploaded
currentRequest.DownloadProgress; //The progress by downloading data from the server
currentRequest.DownloadedBytes; //The number of bytes of body data the system has downloaded
currentRequest.Abort(); //Abort the request manually

Additionally we can run a callback function whenever a progress change happens!

RestClient.Get(new RequestHelper {
  Uri = "https://jsonplaceholder.typicode.com/users", 
  ProgressCallback = percent => Debug.Log(percent)
});

Later we can clear the default headers and params for all requests

RestClient.ClearDefaultHeaders();
RestClient.ClearDefaultParams();

Example

  • Unity as Client
[Serializable]
public class ServerResponse {
  public string id;
  public string date; //DateTime is not supported by JsonUtility
}
[Serializable]
public class User {
  public string firstName;
  public string lastName;
}
RestClient.Post<ServerResponse>("www.api.com/endpoint", new User {
  firstName = "Juan David",
  lastName = "Nicholls Cardona"
}).Then(response => {
  EditorUtility.DisplayDialog("ID: ", response.id, "Ok");
  EditorUtility.DisplayDialog("Date: ", response.date, "Ok");
});
  • NodeJS as Backend (Using Express)
router.post('/', function(req, res) {
  console.log(req.body.firstName)
  res.json({
    id: 123,
    date: new Date()
  })
});

Credits 👍

Contributing ✨

When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated ❤️.
You can learn more about how you can contribute to this project in the contribution guide.

Contributors ✨

Please do contribute! Issues and pull requests are welcome.

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Collaborators

jdnichollsc diegoossa nasdull nasdull
Juan Nicholls Diego Ossa Nasdull Maifee Ul Asad

Supporting 🍻

I believe in Unicorns 🦄 Support me, if you do too.

Donate Ethereum, ADA, BNB, SHIBA, USDT, DOGE:

Wallet address

Wallet address: 0x3F9fA8021B43ACe578C2352861Cf335449F33427

Please let us know your contributions! 🙏

Enterprise 💼

Available as part of the Tidelift Subscription.

The maintainers of RestClient for Unity and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Security contact information 🚨

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

License ⚖️

This repository is available under the MIT License.

Happy coding 💯

Made with ❤️

restclient's People

Contributors

aang521 avatar codacy-badger avatar coeur avatar drazail avatar fegabe avatar jdnichollsc avatar kbobnis avatar kevinsomnia avatar l-naej avatar lyze237 avatar maifeeulasad avatar neegool avatar nepoxx avatar tigerhix 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

restclient's Issues

need help for POST method

This is my code and I am trying to post gender = "male".
but this code is not working for me.

RestClient.Post<Models.RootObjectData> (url, new
{
gender = "male"
}, (err, res,body) => {
if (err != null) {
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
} else {
EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson (body, true), "Ok");
}
});

Model Classes:
[Serializable]
public class Data
{
public int timestamp_created;
public int id;
public string gender;
public string access_token;

	public override string ToString(){
		return UnityEngine.JsonUtility.ToJson (this, true);
	}
}

[Serializable]
public class RootObjectData
{
	public bool status;
	public int statusCode;
	public Data data;
	public string message;


	public override string ToString(){
		return UnityEngine.JsonUtility.ToJson (this, true);
	}
}

"Unknown error"

I was using your Proyecto26 library in Unity project. And it worked pretty well.
Problem showed on 1 Android device.
Then(..) section is never called, and only Catch(..) get called.
where err contains only enigmatic error "Unknown error".

The same app works in Unity and on other phones.

Any hint?

How to post data to server by using key value pair?

I would like to post data to server like ?param1=value1&param2=value2...

But this library seems not supporting it. And I tried put ?param1=value1&param2=value2 to BodyString in RequestHelper, but still not working.

Could anyone help me? thanks in advance.

How to use UnityWebRequest to make REST requests in Unity?

Hi
I am interested in using UnityWebRequest to make REST requests to the Watson Machine Learning( this service is not included in the Watson SDK for Unity at the moment)
Since that Watson SDK for Unity does not support PUT operations( by RESTConnector class), I would need to create a new Class that use UnityWebRequest( this one support PUT operations) to make REST requests to the Watson Machine Learning service, for it, Could I use your Unity Plugin to do it?
Thanks for your time
Alejandro Castan

RestClient.Post<ResultBean<PageBean2<Student>>>(currentRequest) is not working.

RequestHelper currentRequest = new RequestHelper { Uri = "", Body = new User { }, }; RestClient.Post<ResultBean<PageBean2<Bank>>>(currentRequest) .Then(res => { EditorUtility.DisplayDialog("Success", JsonUtility.ToJson(res, true), "Ok"); }) .Catch(err => { EditorUtility.DisplayDialog("Error", JsonUtility.ToJson(err.Message, true), "Ok"); });

Why this library can not parse response entity just like: ResultBean<PageBean2>

But if I use ResultBean, the data can be parsed smoothly.

Please help me.
Thank you all.

Breaks build out of the box

DemoScene\Scripts\MainScript.cs uses EditorUtility so trying to do an actual build breaks as EditorUtility is not present.

Can fix this by wrapping in #if UNITY_EDITOR/#endif.

Is this deliberate or am I missing something? Happy to submit a pull request if former.

Unloading broken assembly Assets/Plugins/myhttp.dll, this assembly can cause crashes in the runtime

**Unloading broken assembly Assets/Plugins/myhttp.dll, this assembly can cause crashes in the runtime
TypeLoadException: Could not load type 'HTTP.HttpClient`2' from assembly 'http, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.**

Hello everyone, I have created a dll file which inclues my own http module.

But when I called that dll from another new project, it occuring above errors.(HTTP.HttpClient is my namespace and filename)

I have included both Proyecto26.RestClient.dll and RSG.Promise.dll when I was creating that dll file(dll file is based on .Net 3.5)
But I guess the issue may comes from these two dll files.

My Unity runtime version: .Net 3.5 and Api level is .net 2.0 subset
(Also tried other version .Net 4.0 but still have this issue)

Could anyone help me?

Thanks in advance.

Poor JsonUtility from UnityEngine

@jdnichollsc One more thing.

I have tried to POST some data to my ASP.NET Core API and every time ModelBinder from MVC failed to bind the incoming JSON to my model object. After some hours of debugging I tried to replace the JsonUtility to JsonConvert from Newtonsoft.Json package and it worked.

Also I can say, that JsonUtility can not serialize/deserialize dictionaries, which is important for me.

The dark side of that (I am not sure) is that JsonUtility may be faster, but I don't think it can compensate missing features or (in my case) just not working with my API (The problem is not from there, because Postman and Swagger working OK when testing).

You will not have any troubles with .NET Framework version, Newtonsoft requires .NET Framework 2.0.

What do you think about this?

Add Support for a specific DownloadHandler

Currently for each UnityWebRequest the DownloadHandlerBuffer are used.
See the extension class

In my unity project i has to download large files (>100mb) to a file on the pc or device.

With the byte buffer download handler the whole content of the file was loaded into the ram and when the download was finished the content can be written to the local file.

For these large files it would be nice to set a download handler manualy to the RequestHelper like this:

string srcUri = "http://myapi/ressource/load/bigfile";
string destPah = Path.Combine(Application.persistentDataPath, "bigfile");

DownloadHandlerFile dh = new DownloadHandlerFile(destPah);
dh.removeFileOnAbort = true;

Proyecto26.RequestHelper request = new Proyecto26.RequestHelper()
    {
        Uri = srcUri,
        DownloadHelper = dh,
    }
;

Proyecto26.RestClient.Get(request)
    .Then(
        () => {
            Debug.Log("Downloaded to " + destPah);
        }
    )
    .Catch(
        err => {
            Debug.Log("Error during download:" + err);
        }
    )
;

In the extension class the options can be checked like this:

if (options.DownloadHelper is DownloadHandler)
    request.downloadHandler = options.DownloadHelper;
else
    request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

To add the download helper to the request helper the request helper needs to become the download helper property like this:

public class RequestHelper {
        public DownloadHandler DownloadHandler { get; set; }
}

There are a lot of useful download helpers out there. Like AssetBundle or Texture, ....

It wold be nice when you can add the support of a configurable download helper.

My currently workaround is to perform the web request by myself without your RestClient (without all the features and much more code).

public static RSG.IPromise LoadRessourceToFile(
    System.Uri url,
    string dest
)
{
    RSG.Promise promise = new RSG.Promise();

    UnityWebRequest request = new UnityWebRequest(url.AbsoluteUri, UnityWebRequest.kHttpVerbGET);

    DownloadHandlerFile dh = new DownloadHandlerFile(dest);
    dh.removeFileOnAbort = true;
    request.downloadHandler = dh;

    StartCoroutine(
        SendRequest(request, promise)
    );

    return promise;
}

private static System.Collections.IEnumerator SendRequest(
    UnityWebRequest request,
    RSG.Promise promise
)
{
    yield return request.SendWebRequest();

    if (request.isNetworkError || request.isHttpError)
        promise.Reject(new Exception(request.error));
    else
        promise.Resolve();

    yield break;
}

Does not work on Unity 5.6.1f1

Unity version: 5.6.1f1
OS: Windows 7
Crashes with error:

MissingMethodException: Method not found: 'UnityEngine.Networking.UnityWebRequest.set_timeout'.
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
Proyecto26.StaticCoroutine:StartCoroutine(IEnumerator)
Proyecto26.RestClient:GetArray(RequestHelper, Action`2)
Proyecto26.RestClient:GetArray(RequestHelper)
MainScript:Get() (at Assets/RestClient/DemoScene/Scripts/MainScript.cs:20)
UnityEngine.EventSystems.EventSystem:Update()

Problems with self-signed SSL certificate

Hello,

I am using RestClient to connect my Unity client application to an Amazon AWS EC2 instance which runs an Nginx Webserver. The server is set up to use TLS. Since I apparently cannot simply create a valid certificate for my AWS-owned domain, I have to use a self-signed certificate.
When I try to connect to the server from Unity (App in editor-mode), every request fails with following error message: "Unable to complete SSL connection"
I highly suspect it has something to do with Unity not accepting my self-signed certificate. The same request works fine when I send it from Postman.

Is there a way to deactivate certificate checks in RestClient, preferably without altering the source code and rebuilding the package?

Thanks for the help

Foo, Bar

I only started learning about JSON maybe 2 weeks ago so this has been a great learning curve for me, still working on deserializing this but will get it soon i hope.

just one question, where does foo and bar fit into this ?

foobar

Scene reload issue

Hi guys,
We use RestClient in our project and stuck to following problem.
As far as we understood when client is making call new Gameobject "StaticCoroutineRestClient " is created.
And it happens that if we load another scene during the call that game object is destroyed and we receive no response.
Is there any solutions or workaround to that problem?
Thanks.

Exception with status code

Hi, I've been using the package for a week now, it's pretty good actually but there's one thing that bothers me, Exception does not have a status code and/or the description from the server.
I've been looking into your code and found that you return the error from UnityWebRequest which does not have neither the status code or a description from the server, in case my server return a 400 (BadRequest) with a description why it has failed. Both of those thing can be gathered pretty ease since you are creating a RequestException and have a RequestHelper in your disposal, which has both of those things.
To make it a little more clear why it's a good "feature" I'll leave a snippet below.

RestClient.Get($"{URL}/test")
            .Then(response => {
                //Do something
                return RestClient.Post($"{URL}/token", model);
            }).Then(response => {
                //Here I can can use the status code and/or the "descrition" from server
                switch (response.statusCode) {
                    case 200:
                        //Success
                        break;
                    case 401:
                        //Unauthorized
                        break;
                    default:
                        //All the others
                        break;
                }
            }).Finally(() => {
                //Do something
            }).Catch(Debug.LogException);

If something goes wrong here (return RestClient.Post($"{URL}/token", model);) the second Then() won't be called, and that's fine, but catching the exception does not help me 'cause it does not say what really happened there

*EDIT

After posting this I realized that even this change won't be enough for some cases. Using my own scenario, when opening the app, the user should log in, he/she might type the wrong email/password, if that is the case, the server will return a 401 (Unauthorized) (or you may want a 400 (BadRequest)), none of those are really an error, at least not a error to be "catchched" (in the Catch()), i would like to have them in the Then(), my case 401: (in the switch) will never be called, since server returned errors are treated as generic errors.

The EDIT part are just some thoughts, I'm not trying to suggest anything, is just, I don't know, my case is "special", (is it?)

UniRx support

It's possible to integrate UniRx using Conditional compilation symbols.
Actions to execute:

  • Move the promises logic to another folder called Promises and add Conditional compilation to detect the dependency.
  • Create a new file in order to import UniRx using Conditional compilation too, we can use Overloaded methods or create different names (check the standard here).

RequestHelper.CertificateHandler missing?

Looking at the documentation it looks like I should be able to set a custom CertificateHandler as a property of the RequestHelper. There appears to be a mismatch with the actual API in release 2.4.1 as there is no definition for a CertificateHandler property.

Exception when DownloadHandlerFile are used

In #28 you have add support for a specific DownloadHandler.
Thank you for the fast implementation!

I tried it out, unfortunately i missed a problem.

For whatever reason, the UnityEngine.Networking.DownloadHandlerFile throws a NotSupportedException for GetData and GetText

When i use the DownloadHandlerFile now, the ResponseHelper tries to get the data and text from the DownloadHelper.
This inevitably leads to the NotSupportedException.

I have checked all Unity build in Downloadhelpers.
The following handlers throw an exception on data and/or text calls:

DownloadHelper GetData GetText
DownloadHandlerAssetBundle NotSupportedException NotSupportedException
DownloadHandlerAudioClip returns byte[] NotSupportedException
DownloadHandlerBuffer returns byte[] returns string
DownloadHandlerFile NotSupportedException NotSupportedException
DownloadHandlerMovieTexture returns byte[] NotSupportedException
DownloadHandlerScript returns null returns string
DownloadHandlerTexture returns null returns string

I can't see a interface or another way to find out if a download handler supports the properties.

So i think the fastest solution is to catch the exceptions like this:

public static Proyecto26.ResponseHelper CreateWebResponse(this UnityWebRequest request)
{
    byte[] data = null;
    try { data = request.downloadHandler.data; }
    catch (NotSupportedException) { }

    string text = "";
    try { text = request.downloadHandler.text; }
    catch (NotSupportedException) { }

    return new Proyecto26.ResponseHelper
    {
        StatusCode = request.responseCode,
        Data = data,
        Text = text,
        Headers = request.GetResponseHeaders(),
        Error = request.error
    };
}

Ore use a helper/wrapper/mapper for that like this:

class DownloadedData
{
	private DownloadHandler _downloadHandler;

	public byte[] data
	{
		get
		{
			try
			{
				return _downloadHandler.data;
			}
			catch (NotSupportedException)
			{
				return null;
			}
		}
	}

	public string text
	{
		get
		{
			try
			{
				return _downloadHandler.text;
			}
			catch (NotSupportedException)
			{
				return "";
			}
		}
	}

	public DownloadedData(DownloadHandler dh)
	{
		_downloadHandler = dh;
	}
}
public static ResponseHelper CreateWebResponse(this UnityWebRequest request)
{
	var responseData = new DownloadedData(request.downloadHandler);

	return new ResponseHelper
	{
		StatusCode = request.responseCode,
		Data = responseData.data,
		Text = responseData.text,
		Headers = request.GetResponseHeaders(),
		Error = request.error
	};
}

Can you fix the issue with a solution that is best for you, please?
Thanks a lot and sorry that i have not seen the problem sooner.

How to retrieve the status code?

My request looks like this:

currentRequest = new RequestHelper
		{
			Uri = basePath + "/login",
			Body = new User
			{
				email = email,
				password = password
			}
		};
		currentRequest.IgnoreHttpException = true;
		RestClient.Post<ServerResponse>(currentRequest)
			.Then(res =>
			{
				Debug.Log("response");
				Debug.Log(res.error);
				Debug.Log(res.StatusCode);
			})
			.Catch(err => {
				Debug.Log(err.GetType());
				Debug.Log(err.GetType().Name);
				Debug.Log(err.Message);
			});

and

[System.Serializable]
public class ServerResponse
{
	[System.Serializable]
	public class UserObject
	{
		public string id;
		public string email;
	}

	public UserObject user;
	public string token;
	public string error;
	public string statusCode;
}

But I always get null for statusCode. How do I access it? Thank you.

No exception when response is error

Hi guys.
The problem is that regardless of what status code comes in response, an exception is not thrown.

RestClient
    .Post(helper, body)
    .Catch(e => error(e))
    .Done(r => callback());

Perhaps I'm doing something wrong, but if the resource is not found, or the request is not authorized, or it was a bad request, there should not be an exception thrown? callback() is always called no matter what was the status code of the response. I even tried an invalid (or empty) host name and there is still no exception.
Thank you.

Now requires .net 4 on Unity

I just installed this, I had a version on an old version of unity from June, but installed latest one on new project today from asset store.

All works fine, my issue is that i now have to set the runtime and api compatibility level to .NET 4.x which increases my apk size by 10MB. Is there any reason it needs this version? If I leave it on .NET 3.5 equivalent and .net 2.0 subset (like my other project is) I get the following error

ArgumentException: The Assembly netstandard is referenced by RSG.Promise ('Assets/RestClient/Packages/RSG.Promise_netstandard.dll'). But the dll is not allowed to be included or could not be found. UnityEditor.AssemblyHelper.AddReferencedAssembliesRecurse (System.String assemblyPath, System.Collections.Generic.List1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary2 cache, BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/AssemblyHelper.cs:155) UnityEditor.AssemblyHelper.FindAssembliesReferencedBy (System.String[] paths, System.String[] foldersToSearch, BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/AssemblyHelper.cs:195) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr

timeout error

hi
what is this error at the start?after click a button

MissingMethodException: Method not found: 'UnityEngine.Networking.UnityWebRequest.set_timeout'.
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
Proyecto26.StaticCoroutine:StartCoroutine(IEnumerator)
Proyecto26.RestClient:GetArray(RequestHelper, Action`2)
Proyecto26.RestClient:GetArray(RequestHelper)
MainScript:Get() (at Assets/MainScript.cs:18)
UnityEngine.EventSystems.EventSystem:Update()
Uploading error.jpg…

tanx in advance to ur attention

IL2CPP builds don't work?

Only happens with IL2CPP, Mono is fine.

My build settings:

image

I get the following error when building an apk:

stdout:
Fatal error in Unity CIL Linker
Mono.Linker.MarkException: Error processing method: 'RSG.IPromise1<Proyecto26.ResponseHelper> Proyecto26.RestClient::Post(Proyecto26.RequestHelper)' in assembly: 'Proyecto26.RestClient.dll' ---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'RSG.Promise, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null' at Unity.IL2CPP.Common.MissingMethodStubber.GetTypeModule(TypeReference type, IEnumerable1 assemblies)
at Unity.Linker.Steps.AddUnresolvedStubsStep.MarkAssemblyOfType(UnityLinkContext context, TypeReference type)
at Unity.Linker.Steps.Marking.UnresolvedStubMarking.HandleUnresolvedType(TypeReference reference)
at Unity.Linker.Steps.UnityMarkStep.HandleUnresolvedType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
at Unity.Linker.Steps.UnityMarkStep.ProcessMethod(MethodDefinition method)
at Mono.Linker.Steps.MarkStep.ProcessQueue()
--- End of inner exception stack trace ---
at Mono.Linker.Steps.MarkStep.ProcessQueue()
at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
at Mono.Linker.Steps.MarkStep.Process()
at Unity.Linker.Steps.UnityMarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.Process(LinkContext context)
at Unity.Linker.UnityDriver.Run()
at Unity.Linker.UnityDriver.RunDriverWithoutErrorHandling()
at Unity.Linker.UnityDriver.RunDriver()
stderr:

and

Exception: C:\Program Files\Unity\Hub\Editor\2018.3.0b7\Editor\Data\il2cpp\build/UnityLinker.exe did not run properly!
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/BuildUtils.cs:130)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action1[T] setupStartInfo) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/BuildUtils.cs:73) UnityEditorInternal.AssemblyStripper.RunAssemblyLinker (System.Collections.Generic.IEnumerable1[T] args, System.String& out, System.String& err, System.String linkerPath, System.String workingDirectory) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/AssemblyStripper.cs:174)
UnityEditorInternal.AssemblyStripper.StripAssembliesTo (System.String[] assemblies, System.String[] searchDirs, System.String outputFolder, System.String workingDirectory, System.String& output, System.String& error, System.String linkerPath, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Collections.Generic.IEnumerable1[T] additionalBlacklist, UnityEditor.BuildTargetGroup buildTargetGroup, UnityEditor.ManagedStrippingLevel managedStrippingLevel) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/AssemblyStripper.cs:121) UnityEditorInternal.AssemblyStripper.RunAssemblyStripper (System.Collections.IEnumerable assemblies, System.String managedAssemblyFolderPath, System.String[] assembliesToStrip, System.String[] searchDirs, System.String monoLinkerPath, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, UnityEditor.RuntimeClassRegistry rcr, UnityEditor.ManagedStrippingLevel managedStrippingLevel) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/AssemblyStripper.cs:305) UnityEditorInternal.AssemblyStripper.StripAssemblies (System.String managedAssemblyFolderPath, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, UnityEditor.RuntimeClassRegistry rcr, UnityEditor.ManagedStrippingLevel managedStrippingLevel) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/AssemblyStripper.cs:198) UnityEditorInternal.IL2CPPBuilder.Run () (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:176) UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:35)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at :0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at :0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at :0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at :0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:286)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Building for IOS Platform occurs error using this library. Android is fine.

Unity version: 2018.2.4 (Have tried in other platform, still got this issue)

Fatal error in Unity CIL Linker
Mono.Linker.MarkException: Error processing method: 'System.Void HTTP.HttpClient`2::Request()' in assembly: 'Assembly-CSharp.dll' --->
Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'RSG.Promise, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null'
�� Unity.Linker.Steps.AddUnresolvedStubsStep.GetTypeModule(TypeReference type, AssemblyDefinition[] assemblies)
�� Unity.Linker.Steps.AddUnresolvedStubsStep.MarkAssemblyOfType(UnityLinkContext context, TypeReference type)
�� Unity.Linker.Steps.UnityMarkStep.HandleUnresolvedType(TypeReference reference)
�� Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)
�� Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
�� Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
�� Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
�� Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
�� Unity.Linker.Steps.UnityMarkStep.ProcessMethod(MethodDefinition method)
�� Mono.Linker.Steps.MarkStep.ProcessQueue()

So I located the code that pointing to Restclient library.

FileNotFoundException: Could not find file "E:\unity-game\testProject\Temp\StagingArea\Data\Managed\tempStrip\RSG.Promise.dll"
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share,
System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at :0)
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share)
(at :0)
(wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
Mono.Cecil.ModuleDefinition.GetFileStream (System.String fileName, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share)
(at <28cdca1704d2491781795499c297b78b>:0)
Mono.Cecil.ModuleDefinition.ReadModule (System.String fileName, Mono.Cecil.ReaderParameters parameters) (at <28cdca1704d2491781795499c297b78b>:0)
Mono.Cecil.AssemblyDefinition.ReadAssembly (System.String fileName, Mono.Cecil.ReaderParameters parameters) (at <28cdca1704d2491781795499c297b78b>:0)
UnityEditor.AssemblyReferenceChecker.CollectReferencesFromRootsRecursive (System.String dir, System.Collections.Generic.IEnumerable1[T] roots, System.Boolean ignoreSystemDlls) (at C:/buildslave/unity/build/Editor/Mono/Utils/AssemblyReferenceChecker.cs:51) UnityEditor.AssemblyReferenceChecker.CollectReferencesFromRootsRecursive (System.String dir, System.Collections.Generic.IEnumerable1[T] roots,

Please help me, thanks in advance.

How can I use the downloaded data outside of the Promise?

Hello !

I am using your wonderful framwork. I try to load the model data from an external server. I am able to download it, but I cannot use the data from outside the Promise structure.

e.g.

`

     RestClient.Request(request).Then(response =>
                {

                    UberDebug.LogChannel(LogChannels.NETWORK, "Received from Server : " + response.Text);
                    responseAsModel = JsonConvert.DeserializeObject<GameContextMessage>(response.Text);


                }).Catch(error => { UberDebug.LogErrorChannel(LogChannels.NETWORK, error.Message); }).Done();

`

The variable responseAsModel is always empty, after filling the data. Can you give me an advice about that? Also I would like to now how I can execute the queries in a synchronous way.

Thank you for your input in advance.

Regards
KB

How do you post Form data using your client in unity ?

I have gone through your documentation and couldn't see any information regarding this. Could you please update some information or post an example of the same. I am trying to create a login page in unity using your plugin but I am not able to do it.

Status comming OK, but values aren't reaching to the server

Hi,

I am not able to figure out that this is my bug or plugin ( most probably I know, this is my own issue,) but still try to help me out.
Sorry, but I don't know what I'm doing wrong, so please guide me once.
I have the following POST REST API
http://vr.azurewebsites.net/api/CustInfoTemps

with params:

{
  "CustomerName": "sample string 2",
  "MobileNo": "123",
  "AccessoriesInterior": "sample string 6",
  "AccessoriesExterior": "sample string 7"
}

This API is working fine in Postman & RestClient

I made a wrapper method so that my all friends use this in the same way :

public static void POSTWebService <T> (string API, object bodyJson, Action<string, bool> callback){
            var requestOptions = new RequestHelper {
                url = API,
                headers = new Dictionary<string, string> {
                    { "Content-Type", "application/json" }
                }
            };
            RestClient.Post<T> (requestOptions, bodyJson, (err, res, body) => {
                if (!String.IsNullOrEmpty (res.error)) {
                    Debug.LogError ("error " + res.error);
                  callback.Invoke (res.error, false);
                } else {
                  callback.Invoke (JsonUtility.ToJson (body, true), true);
                    Debug.Log ("SUcess " + JsonUtility.ToJson (body, true));
                }
            }); 
        }

I'm calling this method with the following code:

WebService.POSTWebService<CarCarConfiguredAPIResut> (http://vrappmahindra.azurewebsites.net/api/CustInfoTemps,
				new {
					CustomerName = "Test",
					MobileNo = 123,
					AccessoriesInterior = "Accessoried",
					AccessoriesExterior = "Exterior"
                                   }, SendDataCallBack
			);	

I am getting the result of success, but the values aren't reflecting in my server.

Please let me know what I'm doing wrong.

not working

hi , i use the following code :
var promise=RestClient.Post<Menu_LoginModel>(url, loginModel).Then(response => { print("done"); }).Catch(err => EditorUtility.DisplayDialog("Error", err.Message, "Ok"));

but its not working ,nothing happes

Error making Android build: dll is not allowed to be included or could not be found.

I am getting this error attempting to make a build for Android:

ArgumentException: The Assembly netstandard is referenced by RSG.Promise ('Assets/RestClient/Packages/RSG.Promise_netstandard.dll'). But the dll is not allowed to be included or could not be found.
UnityEditor.AssemblyHelper.AddReferencedAssembliesRecurse (System.String assemblyPath, System.Collections.Generic.List1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary2 cache, BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/AssemblyHelper.cs:155)
UnityEditor.AssemblyHelper.FindAssembliesReferencedBy (System.String[] paths, System.String[] foldersToSearch, BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/AssemblyHelper.cs:195)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

I tried setting Api Compatibility Level to .NET 2.0 but to no avail. Thanks for your help.

TypeLoad Exception

TypeLoadException: Could not load type 'UnityEngine.Networking.UnityWebRequestAsyncOperation' from assembly 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

"Failure has occurred while loading a type" only on Build

Hi,

First of all, thanks a lot for the library, it has been really enjoyable to use it in my project so far.

I am having an issue and was able to reproduce it in a simple project (https://drive.google.com/open?id=1pUHzQEhPWuEpV1nAer7jUEYJKfdGuosq). The build version is also included. When in the Editor, everything works as expected. However, when I build the project, I receive a "Failure has occurred while loading a type." message and sometimes a message stating it cannot access the web address. I know that the request reaches the server (I confirmed it in the server's logs) and it seems that something is going wrong in the data processing of the response somehow. For other libraries that I use in my project, I have unity set to use the Scripting Runtime version .NET 4.x equivalent and the API Compatibility Level as .NET Standard 2.0.

I also tried to disable the firewall and the same thing happen.

Unfortunately I wasn't able to get a more detailed message or could pinpoint the error. Has anyone had a similar issue? If so, how did you solve it? Am I doing something wrong?

Thank you.

Logging in using RestClient

Hi

My Backend Developer has already created the Login / Registration system.

He is telling me to POST the Username and Password so that i can get the details of the logged in user

RestClient.Post(usersRoute, newUser).Then(customResponse => {
EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(customResponse, true), "Ok");
});

Can you tell me where i can actually add the username and password field over the above method to get access of the user ?

Thanks

Or is there another way ?

RestClient.Post("www.api.com/endpoint", new User {
firstName = "Juan David",
lastName = "Nicholls Cardona"
}).Then(response => {
EditorUtility.DisplayDialog("ID: ", response.id, "Ok");
EditorUtility.DisplayDialog("Date: ", response.date, "Ok");
});

Can i use this in some manner for login ?

The link he gave me to POST is "https://eadmin.avianet.aero/api/v1/login"

Type IPromise<> Error - UWP

I've build my unity project to UWP (because I'm building an Hololens app). But when i want to deploy it to my Hololens via Visual Studio 2017 this error shows up.

Error CS0012 The type 'IPromise<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'RSG.Promise, Version=3.0.0.0, Culture=neutral, PublicKeyToken=7019fe0722eef3a4'.

Unity 3d Version 5.6.3 Error

TypeLoadException: Could not load type 'UnityEngine.Networking.UnityWebRequestAsyncOperation' from assembly 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
Proyecto26.StaticCoroutine:StartCoroutine(IEnumerator)
Proyecto26.RestClient:GetArray(RequestHelper, Action`2)
Proyecto26.RestClient:GetArray(RequestHelper)
MainScript:Get() (at Assets/MainScript.cs:18)
UnityEngine.EventSystems.EventSystem:Update()

I have an urgent question.

Hi.

I'm going to use Post Method to deliver the raw data (byte) to the server.

For reference, the server is a Golang server and tested with two Assets: BestHTTP and Rest Client for Unity.

Below are the results of actual testing ,

Unity C# Code Sample

BestHTTP Sample # 1

HTTPRequest request = new HTTPRequest(new Uri(_builder.ToString()), OnRequestFinished);

    if (json!= null)

    {

      

        byte[] data = SnappyCompress(json);



        request.RawData = data;

}

request.MethodType = HTTPMethods.Post;

    request.Tag = transparent;

    request.Send();

Rest Client for Unity Sample #1

[Serializable]

public class Post

{

    public byte[] data;



    public override string ToString()

    {

        return UnityEngine.JsonUtility.ToJson(this, true);

    }



}

byte[] rawData = SnappyCompress(json);

currentRequest = new RequestHelper

    {

        Uri = url.ToString(),

        Body = new Post

        {

            data = rawData,

        },

    };

    RestClient.Post<Post>(currentRequest)

     Then(res => GetChracter())

    .Catch(err => EditorUtility.DisplayDialog("Error", err.Message, "Ok"));

Rest Client for Unity Sample #2

byte[] rawData = SnappyCompress(json);

  currentRequest = new RequestHelper

    {

        Uri = url.ToString(),

        Body = rawData,

    };

    RestClient.Post (currentRequest)

     Then(res => GetChracter())

    .Catch(err => EditorUtility.DisplayDialog("Error", err.Message, "Ok"));

Rest Client for Unity Sample #3

byte[] rawData = SnappyCompress(json);

    UnityWebRequest www = UnityWebRequest.Put(url.ToString(), rawData);

    www.SetRequestHeader("Content-Type", "application/json");

currentRequest = new RequestHelper

    {

        Uri = url.ToString(),

      Request = www.

    };

    RestClient.Post (currentRequest)

     Then(res => GetChracter())

    .Catch(err => EditorUtility.DisplayDialog("Error", err.Message, "Ok"));

Golang Server Sample Code

rawData, _ := ioutil.ReadAll(c.Request().Body)

      log.Println("rawData: ", len(rawData))





      data, err := snappy.Decode(nil, rawData)



      json := json.RawMessage(string(data))

      log.Println("json - " + string(json))

BestHttp Request Golang Server Response Valid Result Success!

2018/11/19 16:24:24 rawData: 79

2018/11/19 16:24:24 json - {"code":"3","key":"null","name":"Frog","desc":"Example Chracter Desc","exp":2}

Rest Client for Unity Request Golang Server Response Valid Result Failure!

**#1

2018/11/19 16:36:15 user_id: 112807650194621112818

2018/11/19 16:36:15 rawData: 288

2018/11/19 16:36:15 json -

#2

2018/11/19 16:20:15 rawData: 2

2018/11/19 16:20:15 json -

#3

2018/11/19 16:00:06 rawData: 0

2018/11/19 16:00:06 json -**

This results are different.

Is there any way you can get results like BestHTTP?

Tell me how to do it

Snappy is a high-speed compression algorithm created by Google that significantly reduces packet size and is used in big data.

I understand, I'll re-establish that issue with Github, and I hope it's resolved quickly

Thank you.

Nested requests and conditions

Hi,

I have a problem with nested requests. I would like to put conditions in .Then() function but I can't manage to do it. Here is my code:

RestClient.Get(GameManager.SERVER_URL + "/users?login=" + loginUser)
                .Then(res =>
                {
                    IPromise<ResponseHelper> post = null;

                    bool isAvailable = bool.Parse(res.Text);
                    if (isAvailable)
                    {
                        post = RestClient.Post(GameManager.SERVER_URL + "/users", new User { Login = loginUser });
                    }
                    else
                    {
                        Debug.Log("login taken");
                        LoginMessage.color = Color.red;
                    }
                    return post;
                })
                .Then(res =>
                {
                    bool isCreated = bool.Parse(res.Text);
                     ...
                }, 
                rejected =>
                {
                })
                .Catch(err =>
                {
                    GameManager.ShowNetworkError();
                    Debug.Log(err);
                })
                .Finally(() => PopupManager.HidePrefabPopup("LoadingPopup"));

I think it crashes because of post variable which is null when we enter the "else" condition.
Can you help me to use conditions with your project? Thanks in advance

How to correctly include PNG into formData?

RestClient.Post(new RequestHelper {
    Uri = api + "/Documents/1/file",
    FormSections = new List<IMultipartFormSection>() { 
        new MultipartFormFileSection(File.ReadAllBytes(Application.streamingAssetsPath + "/test.png"))
    }
}).Then(r => {
    Debug.Log("uploaded");
}).Catch(err => Debug.Log(err.Message));

Doesn't work for me...

Unable to complete SSL connection (iPhone)

On iOS I seem to get stuck while calling RestClient.get(Request helper).

The helper also has helper.Timeout = 5000;

After getting stuck for 3-5 minutes it'll properly give Unable to complete SSL connection message. Error code 0. Seems to be related to my Cellular Data. If it's on I'll get this problem. If Cellular Data is disabled or disabled just for my app I'll quickly get a No Internet Connection message. Shouldn't the timeout parameter make it quickly fail after 5000 milliseconds?

Also, the iPhone does not have a data plan even though you can enable Cellular Data.

Working on all Platforms except WebGL

Hi
pppp

Amazing Package and does the job quite well.

But whenever i try to Call it on a WebGL , it shows no data.

Can you tell me as to if i need an additional .dll file or any specific settting for that platform ?

Thanks

change from Editor Utility to GameObject

button

Not sure but it seems like a Same problem.
I am beginner in programming that’s why bit stuck. And the Error is
Assets\RestClient\DemoScene\Scripts\MainScript.cs(23,13): error CS0103: The name 'EditorUtility' does not exist in the current context

As of I know about the error : Editor Utility is not supporting the display dialog I guess and if want to display the result on a specific Text box game object how to do it. If you could help me out that would be amazing.

And i am using Holographic buttons in my project and on the Click event i am calling REST apis (Only GET for time being). I want to call from my button and result should be available on the UI TEXT prefab (Microsoft provided interactable objects ) So how should i point it to my GameObject (UITextPrefab) rather than Unity UI. Editor Uitlity is not allowing me to display and click event should be HolographicButton.

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.