styly-dev / WebRequest_VisualScriptingNodes

Visual Scripting Nodes and a handy wrapper for the Unity WebRequest class
MIT License
2 stars 0 forks source link

Visual Scripting Nodes for WebRequest

Note: This is a fork of adrenak's http which is a fork of Dubit's unity-http

What is it?

Visual Scripting Node library for Webrequest which is based on Http Unity package developed by Dubit. The Http system has a quick and easy API for making http requests within Unity. The Http instance will run the WebRequest coroutines for you so you don't have to create it per request.

WebRequestVisualScriptingNodes

Installation

Prerequisites : Node.js v16 or above

# Install openupm-cli
npm install -g openupm-cli

# Go to your unity project directory
cd YOUR_UNITY_PROJECT_DIR

# Install package: com.styly.webrequest-visualscripting-nodes
openupm add com.styly.webrequest-visualscripting-nodes

How to use with Visual Scripting

Find the WebRequest custom nodes in WebRequest category with the fuzzy finder.

Get Text node

Get Text

Get Texture node

Get Texture

Get AudioClip node

Get Audio Clip

Progress

Progress

POST node

To be implemented

POST Texture node

To be implemented

Samples (Visual Scripting)

How to install samples

Click Import button at Window - Package Manager - Packages in Project - WebRequest Visual Scripting - Samples

Sample Music:

Features

Original features

New features

Requirements

How to use Http with C# code

If you are using an AssemblyDefinition then reference the Http Assembly.
Import the namespace using STYLY.Http;

// Get text
var request = Http.Get("http://YOURWEBSITE.com/xxxxx.txt")
 .UseCache(CacheType.UseCacheAlways)
 .SetHeader("Authorization", "username:password")
 .OnSuccess(response => Debug.Log(response.Text))
 .OnError(response => Debug.Log(response.StatusCode))
 .OnDownloadProgress(progress => Debug.Log(progress))
 .Send();
//  You may want to use CacheType.UseCacheOnlyWhenOffline option for data feed like RSS or RestAPI

var request = Http.Get("http://YOURWEBSITE.com/xxxxx.json")
 .UseCache(CacheType.UseCacheOnlyWhenOffline) // <= Load data from cache only when offline
 .SetHeader("Authorization", "username:password")
 .OnSuccess(response => Debug.Log(response.Text))
 .OnError(response => Debug.Log(response.StatusCode))
 .OnNetworkError(response => Debug.Log("Network Error"))
 .OnDownloadProgress(progress => Debug.Log(progress))
 .Send();
// Get Texture 
var request = Http.GetTexture("http://YOURWEBSITE.com/xxxxx.jpg")
 .UseCache(CacheType.UseCacheAlways)
 .OnSuccess(response => {
     Debug.Log(response.Texture.width);
     Debug.Log(response.Texture.height);
 })
 .OnError(response => Debug.Log(response.StatusCode))
 .OnDownloadProgress(progress => Debug.Log(progress))
 .Send();
// Get AudioClip 
var request = Http.GetAudioClip("http://YOURWEBSITE.com/xxxxx.mp3")
 .UseCache(CacheType.UseCacheAlways)
 .OnSuccess(response => {
     Debug.Log(response.AudioClip.frequency);
 })
 .OnError(response => Debug.Log(response.StatusCode))
 .OnDownloadProgress(progress => Debug.Log(progress))
 .Send();
// Cache file will be generated based of its URL. So if signed URL is used, a cache file will be created every time since Signed URL changes for each access even for the same content. There are several options to avoid it. 

string url = "https://storage.googleapis.com/aaaaaa/bbbbbb/cccccc.png?Expires=11111111&GoogleAccessId=dddddd&Signature=eeeeeeee"
string[] ignorePatterns;

// Option A: You can set ignore patterns manually.
ignorePatterns = new string[] {
    // for Google Cloud Storage
    "(Expires=[^&]+&?|GoogleAccessId=[^&]+&?|Signature=[^&]+&?)", 
    // for Amazon CloudFront
    "(Expires=[^&]*&?|Signature=[^&]*&?|Key-Pair-Id=[^&]*&?)",  
    // for Azure Blob Storage
    "(se=[^&]*&?|sp=[^&]*&?|sv=[^&]*&?|sr=[^&]*&?|sig=[^&]*&?)"
};

// Option B: You can use the following method to get ignore patterns of signed URLs for major cloud service.
ignorePatterns = CacheUtils.GetSignedUrlIgnorePatters();

var request = Http.Get(url)
.UseCache(CacheType.UseCacheAlways, ignorePatterns)
.OnSuccess(response => Debug.Log(response.Text))
.OnError(response => Debug.Log(response.StatusCode))
.OnDownloadProgress(progress => Debug.Log(progress))
.Send();

// Option C: Set `USE_CLOUD_SIGNED_URL_IN_CACHEUTILS` in `Project Settings` - `Player` - `Scripting Define Symbols`
// Asynchronous call
async void Start()
{
    var url = "http://YOURWEBSITE.com/xxxxx.txt";
    STYLY.Http.Service.HttpResponse httpResponse = await Http.Get(url)
        .UseCache(CacheType.UseCacheAlways)
        .OnSuccess(response => Debug.Log(response.Text))
        .OnError(response => Debug.Log(response.StatusCode))
        .OnDownloadProgress(progress => Debug.Log(progress))
        .SendAsync();

    Debug.Log("Web request task completed.");
    Debug.Log(httpResponse.Text);
}

API

Http Static Methods

All these methods return a new HttpRequest.

Get

Post

Post JSON

Put

Misc

Http Request Configuration Methods

All these methods return the HttpRequest instance.

Headers

Events

Progress

Configure

Data cache

Redirect limit subject to Unity's documentation.

Progress events will invoke each time the progress value has increased, they are subject to Unity's documentation.

Http Request

Http Response

The callbacks for OnSuccess, OnError and OnNetworkError all return you a HttpResponse.
This has the following properties:

Properties

Super Headers

Super Headers are a type of Header that you can set once to automatically attach to every Request you’re sending.
They are Headers that apply to all requests without having to manually include them in each HttpRequest SetHeader call.

JSON Response Example

In this given example, the response.Text from http://mywebapi.com/user.json is:

{
    "id": 92,
    "username": "jason"
}

Create a serializable class that maps the data from the json response to fields

[Serializable]
public class User
{
    [SerializeField]
    public int id;
    [SerializeField]
    public string username;
}

We can listen for the event OnSuccess with our handler method HandleSuccess

var request = Http.Get("http://mywebapi.com/user.json")
    .OnSuccess(HandleSuccess)
    .OnError(response => Debug.Log(response.StatusCode))
    .Send();

Parse the response.Text to the serialized class User that we declared earlier by using Unity's built in JSONUtility

private void HandleSuccess(HttpResponse response)
{
     var user = JsonUtility.FromJson<User>(response.Text);
     Debug.Log(user.username);
}