# Request

`com.jsmacrosce.jsmacros.core.library.impl.FRequest`

**Since:** 1.1.8

Sends HTTP requests and creates WebSocket handlers through the `Request` script library.  
 
 An instance of this class is passed to scripts as the `Request` variable.  
 The [get(String)](#com.jsmacrosce.jsmacros.core.library.impl.FRequest_get-String-) and [post(String, String)](#com.jsmacrosce.jsmacros.core.library.impl.FRequest_post-String-String-) methods send one-call requests;  
 [create(String)](#com.jsmacrosce.jsmacros.core.library.impl.FRequest_create-String-) returns a configurable HTTP request handler, and
 [createWS(String)](#com.jsmacrosce.jsmacros.core.library.impl.FRequest_createWS-String-) creates a WebSocket handler that connects only when asked.  
 HTTP calls block until a response or connection failure; HTTP error status codes are responses,  
 not connection failures. Response text is cached after its first read.  
 ```js
// the quick form: one call, one response
const response = Request.get("https://example.com/api/status");  
print(`status ${response.responseCode}: ${response.text()}`);  

// the builder form is for anything the quick form does not cover
const request = Request.create("https://example.com/api/echo")
  .addHeader("User-Agent", "JsMacrosCE")
  .setConnectTimeout(5000)
  .setReadTimeout(5000);  
print(`posted, status ${request.post("hello").responseCode}`);  

// the quick forms take headers as a java Map rather than as a script object,  
// so the map has to be built through JavaUtils
const headers = JavaUtils.createHashMap();  
headers.put("Accept", "application/json");  
print(`with headers, status ${Request.post("https://example.com/api/echo", "hello", headers).responseCode}`);  

// a websocket installs its handlers by writing to public fields, then connects
const socket = Request.createWS("wss://example.com/socket");  
socket.onTextMessage = JavaWrapper.methodToJava(function (ws, text) {
  print(`from the socket: ${text}`);  
});  
socket.connect();  
 ```

Accessible in scripts via the global `Request` variable.

## Methods

### create {#com.jsmacrosce.jsmacros.core.library.impl.FRequest_create-String-}

```js
create(String url): HTTPRequest
```

Creates a configurable HTTP request handler for the URL. The request is not sent until a send method is called.

**Parameters:**
- `url`: the request URL

**Returns:** a handler for configuring and sending requests to the URL

**Since:** 1.1.8

### createWS {#com.jsmacrosce.jsmacros.core.library.impl.FRequest_createWS-String-}

```js
createWS(String url): Websocket
```

Creates a WebSocket handler without connecting it. Callbacks are read when their events
 occur, so assign them before the events they should handle. The client invokes each
 callback wrapper for its event; script execution and whether the invocation waits depend
 on the wrapper's scheduling mode. Calling [Websocket.connect()](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/impl/classes/Websocket.md#com.jsmacrosce.jsmacros.core.library.impl.classes.Websocket_connect-) performs the
 handshake on that call's thread.  
 ```js
const socket = Request.createWS("wss://example.com/socket");  

// the handlers are public fields, so they are installed by assignment
socket.onTextMessage = JavaWrapper.methodToJava(function (ws, text) {
  print(`received: ${text}`);  
  ws.sendText(`echo: ${text}`);  
});  
socket.onError = JavaWrapper.methodToJava(function (ws, error) {
  print(`the socket failed: ${error}`);  
});  

// and connecting is a separate step
socket.connect();  
// later
socket.close();  
 ```

**Parameters:**
- `url`: the websocket address to open

**Returns:** a handler that has not yet connected

**Since:** 1.2.7

**See:**
- [Websocket](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/impl/classes/Websocket.md)

### get {#com.jsmacrosce.jsmacros.core.library.impl.FRequest_get-String-}

```js
get(String url): HTTPRequest.Response
```

Sends a GET request without custom headers. The call blocks until a response or connection failure.

**Parameters:**
- `url`: the request URL

**Returns:** the response

**Since:** 1.1.8

### get {#com.jsmacrosce.jsmacros.core.library.impl.FRequest_get-String-Map-}

```js
get(String url, Map<String, String> headers): HTTPRequest.Response
```

Sends a GET request to the URL.  
 

 The headers are a Java [Map](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html), not a script object, so they have to be built through
 `JavaUtils.createHashMap()` rather than written as an object literal. The map is
 copied, so changing it afterwards does not change the request. Passing `null` for it
 is the same as using the no header form.  

 The call blocks until the server answers or the connection fails, and a failed connection
 is an [IOException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/IOException.html) rather than a response with a bad status. A response that came
 back with an error status is not a failure here, it is a response with a
 `responseCode` to check.  
 ```js
// headers are a java Map, so they are built through JavaUtils rather than
// written as a script object
const headers = JavaUtils.createHashMap();  
headers.put("Accept", "application/json");  
headers.put("User-Agent", "JsMacrosCE");  

const response = Request.get("https://example.com/api/status", headers);  
if (response.responseCode === 200) {
  print(response.text());  
} else {
  print(`the server said ${response.responseCode}`);  
}
// an unreachable host is an exception, not a bad status
try {
  Request.get("https://not-a-real-host.invalid/");  
} catch (error) {
  print(`that one did not get that far: ${error}`);  
}
 ```

**Parameters:**
- `url`: the URL to send the request to
- `headers`: the request headers as a java Map, or `null` for none

**Returns:** the response, including its status code

**Since:** 1.1.8

**See:**
- [HTTPRequest.Response](../../../../../../../classes/com/jsmacrosce/jsmacros/core/library/impl/classes/HTTPRequest.Response.md)

### post {#com.jsmacrosce.jsmacros.core.library.impl.FRequest_post-String-String-}

```js
post(String url, String data): HTTPRequest.Response
```

Sends a POST request without custom headers. The call blocks until a response or connection failure.

**Parameters:**
- `url`: the request URL
- `data`: the request body

**Returns:** the response

**Since:** 1.1.8

### post {#com.jsmacrosce.jsmacros.core.library.impl.FRequest_post-String-String-Map-}

```js
post(String url, String data, Map<String, String> headers): HTTPRequest.Response
```

Sends a POST request to the URL.  
 

 The headers are a Java [Map](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html) rather than a script object, the same as on the GET form,  
 and the data is sent as the request body with no content type set for it, so an endpoint
 that needs one wants the builder form and its `addHeader`. The call blocks until the
 server answers, and a connection failure is an [IOException](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/IOException.html).  
 ```js
// the body is the second argument, and the headers are a java Map
const headers = JavaUtils.createHashMap();  
headers.put("Content-Type", "text/plain");  
const response = Request.post("https://example.com/api/echo", "hello", headers);  
print(`status ${response.responseCode}, echoed back as ${response.text()}`);  
 ```

**Parameters:**
- `url`: the URL to send the request to
- `data`: the request body
- `headers`: the request headers as a java Map, or `null` for none

**Returns:** the response, including its status code

**Since:** 1.1.8
