> ## Documentation Index
> Fetch the complete documentation index at: https://docs-unity.molca.id/llms.txt
> Use this file to discover all available pages before exploring further.

# HttpClient and HttpRequestAsset

> Async HTTP, ScriptableObject-defined endpoints, and integration with session code.

**Files:**

* `Packages/com.molca.core/Runtime/Networking/Http/HttpClient.cs`
* `Packages/com.molca.core/Runtime/Networking/Http/HttpRequestAsset.cs`

## When to use

* **`HttpRequestAsset`** (recommended) — for data-driven endpoints where URL, method, headers, and body templates live in a ScriptableObject. Best for stable API calls configured once in the Inspector.
* **`HttpRequestBuilder`** (programmatic) — for dynamic endpoints or when URL/body must be built at runtime. Uses a fluent builder API.
* Both route through the same `HttpClient` subsystem with queuing, concurrency control, and connection error events.

## HttpClient

`RuntimeSubsystem` — async HTTP with request queuing, auth header management, and event hooks.

> ⚠️ **The static `HttpClient.*` API is deprecated.** All static members (`SendAsync`, `Send`, `CreateRequest`, `BaseUrl`, events, etc.) are marked `[Obsolete]`. Use the **`IHttpClient` instance interface** instead:
>
> ```csharp theme={null}
> var http = RuntimeManager.GetService<IHttpClient>();
> ```
>
> Or inject via `[Inject] IHttpClient http;`

### IHttpClient (recommended)

| Member                  | Signature                                                                                                                            | Description                                                  |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ |
| `BaseUrl`               | `string BaseUrl { get; }`                                                                                                            | Base URL from configured `HttpModule`, or empty              |
| `MaxConcurrentRequests` | `int MaxConcurrentRequests { get; }`                                                                                                 | Max concurrent in-flight requests                            |
| `ActiveRequestCount`    | `int ActiveRequestCount { get; }`                                                                                                    | Number of requests currently in flight                       |
| `RequestHistory`        | `IReadOnlyList<HttpRequestContext> RequestHistory { get; }`                                                                          | Completed-request history                                    |
| `SendAsync`             | `Awaitable<HttpResponse> SendAsync(HttpRequest request, CancellationToken ct = default)`                                             | Send and await response with optional cancellation           |
| `Send`                  | `void Send(HttpRequest req, CancellationToken ct, Action<HttpResponse> onSuccess, Action<string> onError, Action<float> onProgress)` | Callback-style send with cancellation                        |
| `CreateRequest`         | `HttpRequestBuilder CreateRequest()`                                                                                                 | Start a fluent builder chain                                 |
| `AddDefaultHeader`      | `void AddDefaultHeader(string key, string value)`                                                                                    | Add header to all future requests                            |
| `RemoveDefaultHeader`   | `void RemoveDefaultHeader(string key)`                                                                                               | Remove a default header                                      |
| `ClearDefaultHeaders`   | `void ClearDefaultHeaders()`                                                                                                         | Clear all default headers                                    |
| `CancelAllRequests`     | `void CancelAllRequests()`                                                                                                           | Abort all active and queued requests                         |
| `AddInterceptor`        | `void AddInterceptor(IHttpRequestInterceptor interceptor)`                                                                           | Register a request interceptor                               |
| `RemoveInterceptor`     | `void RemoveInterceptor(IHttpRequestInterceptor interceptor)`                                                                        | Remove a previously registered interceptor                   |
| `SetRetryPolicy`        | `void SetRetryPolicy(HttpRetryPolicy policy)`                                                                                        | Override retry policy (null restores module default)         |
| `SetTransport`          | `void SetTransport(IHttpTransport transport)`                                                                                        | Replace transport (null restores `UnityWebRequestTransport`) |
| `ClearHistory`          | `void ClearHistory()`                                                                                                                | Clears the request history                                   |

**Events:** `RequestStarted`, `RequestCompleted`, `RequestFailed`, `ConnectionError` (instance `event Action`).

### Legacy static API (deprecated)

The following static members on `HttpClient` still compile but are `[Obsolete]` — migrate to the `IHttpClient` instance pattern above.

| Member                              | Migration                     |
| ----------------------------------- | ----------------------------- |
| `HttpClient.SendAsync(request)`     | `http.SendAsync(request)`     |
| `HttpClient.Send(...)`              | `http.Send(...)`              |
| `HttpClient.CreateRequest()`        | `http.CreateRequest()`        |
| `HttpClient.AddDefaultHeader(k, v)` | `http.AddDefaultHeader(k, v)` |
| `HttpClient.BaseUrl`                | `http.BaseUrl`                |
| `HttpClient.OnRequestStarted`       | `http.RequestStarted`         |
| `HttpClient.SetRetryPolicy(p)`      | `http.SetRetryPolicy(p)`      |

## HttpRequestAsset

ScriptableObject describing URL, method, headers, and body templates. Create via **Molca → Networking → HTTP Request**.

| Method          | Signature                                                                                     | Description                                    |
| --------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `SendAsync`     | `async Awaitable<HttpResponse> SendAsync()`                                                   | Send this asset's configured request           |
| `Send`          | `void Send(Action<HttpResponse> onSuccess, Action<string> onError, Action<float> onProgress)` | Callback-style send                            |
| `CreateBuilder` | `HttpRequestBuilder CreateBuilder()`                                                          | Clone into a builder for runtime modifications |
| `Validate`      | `bool Validate(out string[] errors)`                                                          | Check configuration before sending             |

## Code

**From a `HttpRequestAsset`** (recommended when the request is mostly data-driven):

```csharp theme={null}
using Molca.Networking.Http;
using UnityEngine;

public class ProfileClient : MonoBehaviour
{
    [SerializeField] private HttpRequestAsset fetchProfile;

    private async void Start()
    {
        await RuntimeManager.WaitForInitialization();
        var response = await fetchProfile.SendAsync();
        if (response.IsSuccess)
            Debug.Log(response.Text);
    }
}
```

**Programmatic** requests using the fluent builder (preferred — uses `IHttpClient`):

```csharp theme={null}
using Molca.Networking.Http;
using Molca;
using UnityEngine;

public class DynamicApiClient : MonoBehaviour
{
    [Inject] private IHttpClient _http;

    private async void Start()
    {
        await RuntimeManager.WaitForInitialization();
        if (_http == null) return;

        var response = await _http.CreateRequest()
            .Method(HttpMethod.GET)
            .Url("/api/users/42")
            .Header("Accept", "application/json")
            .Timeout(10)
            .SendAsync();

        if (response.IsSuccess)
            Debug.Log(response.Text);
        else
            Debug.LogError(response.ErrorMessage);
    }
}
```

## API Reference

### IHttpClient (instance API)

See the [IHttpClient table](#IHttpClient-recommended) above. Resolve via:

```csharp theme={null}
var http = RuntimeManager.GetService<IHttpClient>();
// Or inject:
[Inject] private IHttpClient _http;
```

### HttpRequestAsset

| Method          | Signature                                                                                     | Description                                    |
| --------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `SendAsync`     | `async Awaitable<HttpResponse> SendAsync()`                                                   | Send this asset's configured request           |
| `Send`          | `void Send(Action<HttpResponse> onSuccess, Action<string> onError, Action<float> onProgress)` | Callback-style send                            |
| `CreateBuilder` | `HttpRequestBuilder CreateBuilder()`                                                          | Clone into a builder for runtime modifications |
| `Validate`      | `bool Validate(out string[] errors)`                                                          | Check configuration before sending             |

### HttpRequestBuilder

| Method      | Signature                                             | Description                              |
| ----------- | ----------------------------------------------------- | ---------------------------------------- |
| `Method`    | `HttpRequestBuilder Method(HttpMethod method)`        | Set HTTP method (GET, POST, PUT, DELETE) |
| `Url`       | `HttpRequestBuilder Url(string url)`                  | Set relative or absolute URL             |
| `FullUrl`   | `HttpRequestBuilder FullUrl(string url)`              | Set absolute URL, bypassing BaseUrl      |
| `Header`    | `HttpRequestBuilder Header(string key, string value)` | Add a request header                     |
| `Body`      | `HttpRequestBuilder Body(string body)`                | Set request body content                 |
| `Timeout`   | `HttpRequestBuilder Timeout(int seconds)`             | Set request timeout                      |
| `SendAsync` | `async Awaitable<HttpResponse> SendAsync()`           | Build and send the request               |

## Troubleshooting

* **Request fails silently:** subscribe to `HttpClient.OnRequestFailed` or `OnConnectionError` for diagnostics. The request may have been queued but not started if `MaxConcurrentRequests` is exceeded.
* **Auth header missing on requests:** call `HttpClient.AddDefaultHeader("Authorization", "Bearer " + token)` after login. Default headers are applied to all future requests automatically.
* **Wrong base URL:** `BaseUrl` comes from `HttpModule` on [Global Settings](/setup/global-settings). If the module is missing, URLs must be absolute (set `useFullUrl = true` or use `FullUrl()` on the builder).
* **Request validation fails:** `HttpRequestAsset.Validate(out errors)` will return `false` if the URL is empty or malformed. Check the `errors` array for specifics.

## Related

* [DataManager](/core/data-manager) — for persistent data providers rather than one-off requests
* [Scenario network config](/vr/scenario-network-config) — VR session HTTP endpoints
* [Global Settings](/setup/global-settings) — `HttpModule` base URL and defaults
* [Recipe: Integrate HTTP requests with data persistence](/recipes/integrate-http-data-persistence) — step-by-step guide to combining HttpClient and DataManager for API calls with local caching

## Unity Editor

<Frame caption="HttpRequestAsset — endpoint definition in Inspector">
  <img src="https://mintcdn.com/ptmolcateknologinusantara/jus_XMBZ8O0U_mpA/images/features/core/http-request-asset-inspector.png?fit=max&auto=format&n=jus_XMBZ8O0U_mpA&q=85&s=621f6aae28ba378898dddcab0a440375" alt="Http Request Asset Inspector" width="704" height="532" data-path="images/features/core/http-request-asset-inspector.png" />
</Frame>
