# Networking and HTTP

> No high-level HTTP client — use java.net/OkHttp off the paint thread, JSON with Jackson.

Source: https://crossfly.dev/docs/data-and-services/networking-http — CrossFly documentation. Full docs as one file: https://crossfly.dev/llms-full.txt

# Networking and HTTP

Another honest page: **the framework does not ship a high-level HTTP client** (no ergonomic `Http.get()`
exposed to the app). You use **`java.net`** or a lib (OkHttp is already on the classpath, used
internally by the maps).

## The mandatory rule
**Make the request off the paint thread** and **return with `Component.onUI(...)`** to touch the UI (see
[Background work](/docs/data-and-services/background-work)).

## Download bytes — `Utils.getRemoteFile(url)`
Shortcut to download a URL's content:
```java
new Thread(() -> {
   byte[] dados = Utils.getRemoteFile("https://api.exemplo.com/dados");  // null on error OR on WebGL
   if (dados == null) { Component.onUI(() -> Hint.show("Falha na rede", 2000)); return; }
   String corpo = new String(dados);
   Component.onUI(() -> mostrar(corpo));
}).start();
```
> ⚠️ `getRemoteFile` returns **`null`** on HTTP error, exception **and on WebGL/TeaVM** — always check.

## JSON with Jackson (not Gson)
The project standard is **Jackson** (`com.fasterxml.jackson.databind.ObjectMapper`):
```java
ObjectMapper mapper = new ObjectMapper();
new Thread(() -> {
   try {
      byte[] json = Utils.getRemoteFile("https://api.exemplo.com/clientes");
      if (json == null) return;
      List<Cliente> clientes = mapper.readValue(json, new TypeReference<List<Cliente>>(){});
      Component.onUI(() -> lista.setItems(clientes));
   } catch (Exception e) { Debug.log("parse: " + e); }
}).start();
```

## GET/POST with `java.net`
When you need control (headers, POST), use `HttpURLConnection`/OkHttp directly — always on a
background thread, result back with `onUI(...)`.

## ⚠️ WebGL/TeaVM limitations
On the Web target, HTTP calls have **restrictions** (CORS, no direct sockets) and `getRemoteFile` returns
`null`. Handle that case or disable the feature on Web (see [platforms](/docs/platforms)).

## Best practices
- **Never** do networking on the paint thread — the UI freezes.
- **Jackson**, not Gson (consistency with the rest of the project).
- Check `null`/exception on every response; show the error to the user via `Hint`/`Alert`.

## Common mistakes
- Looking for `Http.get()`/a ready-made client — it doesn't exist; use `java.net`/OkHttp.
- Ignoring that `getRemoteFile` is `null` on WebGL.
- Parsing/touching the UI directly on the network thread (without `onUI`).

## See also
- [Background work](/docs/data-and-services/background-work) · [State management](/docs/data-and-services/state-management)
