# Chamar outros servidores com REQUEST e guardar ficheiros com DOWNLOAD

> Use REQUEST() para chamadas HTTP de baixo nível com controlo total do método, cabeçalhos, query e corpo, e DOWNLOAD() para transferir um ficheiro remoto para o disco.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: pt
Content-SHA256: 06a5f5b28ffcdeb647c50ca6986097f010f992b09efa09801397c643a8b6572e
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`REQUEST(options)` é o cliente HTTP de baixo nível sobre o qual o `RESTBuilder` é construído. Passe-lhe um objeto e use `await` (ou dê-lhe um callback como segundo argumento). As opções úteis são `url`, `method` (por omissão `GET`), `query` (um objeto, acrescentado ao URL), `headers`, `cookies`, `body` (uma string ou um Buffer), `type` (`json`, `text`, `html`, `xml`, `urlencoded` ou `raw`, que define o `content-type`), `timeout` em milissegundos e `noredirect`.

O resultado é um objeto com `status`, `headers`, `cookies` e `body` (uma string; interprete o JSON você mesmo com `.parseJSON()`). Uma resposta com um estado de erro como 404 **não** é um erro: verifique `status`. A promessa só é rejeitada quando falha o próprio pedido (ligação recusada, timeout, host inválido).

`DOWNLOAD(url, filename)` escreve a resposta em streaming num ficheiro e resolve-se com `{ status, size, filename }`. Não olha para o estado, por isso verifique-o antes de usar o ficheiro.

```js controllers/request.js
exports.install = function() {
	ROUTE('GET /remote/', remote);
	ROUTE('POST /remote/ @json', remote_post);
	ROUTE('GET /remote/text/', remote_text);
	ROUTE('GET /call/', call);
	ROUTE('GET /download/', download);
};

function remote($) {
	$.json({ hello: 'world', name: $.query.name || null });
}

function remote_post($) {
	$.json({ received: $.body, token: $.headers['x-token'] || null });
}

function remote_text($) {
	$.plain('first line\nsecond line\n');
}

async function call($) {

	var get = await REQUEST({ url: $.hostname('/remote/'), query: { name: 'Louis' } });
	var post = await REQUEST({ method: 'POST', url: $.hostname('/remote/'), type: 'json', body: JSON.stringify({ a: 1 }), headers: { 'x-token': 'abc' } });
	var missing = await REQUEST({ url: $.hostname('/does-not-exist/') });

	var failed = null;
	try {
		await REQUEST({ url: 'http://127.0.0.1:1/' });
	} catch (e) {
		failed = true;
	}

	$.json({
		get: get.body.parseJSON(),
		post: post.body.parseJSON(),
		status: [get.status, missing.status],
		failed: failed
	});
}

async function download($) {
	var filename = PATH.tmp('forge-download.txt');
	var response = await DOWNLOAD($.hostname('/remote/text/'), filename);
	var content = require('fs').readFileSync(filename).toString('utf8');
	$.json({ status: response.status, size: response.size, content: content });
}
```
