Skip to content

HttpRes response object

Every time you call an HttpCli verb method, it returns an HttpRes object containing the response data and metadata.

Example Usage

ts
var hc = new HttpCli();
var res = hc.Url("https://www.example.com").Timeout(30).Get();
// "res" is an HttpRes object with its own methods

The HttpRes object provides the following methods:

IsValid

ts
res.IsValid(): boolean;

Returns true if the HTTP/HTTPS call completed, or false otherwise (e.g., if the call timed out).

StatusCode

ts
res.StatusCode(): number;

Returns the HTTP status code from the response (e.g., 200 for success, 201 for created, 403 for forbidden, 404 for not found, 500 for server error). See HTTP status codes for details.

BodyAsString

ts
res.BodyAsString(): string;

Returns the response body as a string (useful for web pages, JSON, etc.).

BodyAsBytes

ts
res.BodyAsBytes(): number[];

Returns the response body as an array of bytes (useful for binary data, such as images).

BodySaveToFile

ts
res.BodySaveToFile(filePath: string): boolean;

Saves the response body to the specified file path. Returns true if successful, false otherwise.

ContentType

ts
res.ContentType(): string;

Returns the MIME Content-Type reported by the server.

ContentLength

ts
res.ContentLength(): number;

Returns the Content-Length reported by the server (may be missing for some responses).

Encoding

ts
res.Encoding(): string;

Returns the Content-Transfer-Encoding reported by the server (may be missing for some responses).

Headers

ts
res.Headers(): object;

Returns a JSON object with all response headers as properties. Example:

json
{
  "Cache-Control": "max-age=604800",
  "Content-Type": "text/html; charset=UTF-8",
  "Date": "Sun, 30 Aug 2020 16:24:06 GMT",
  // ...
}

Cookies

ts
res.Cookies(): object[];

Returns an array of objects, each representing a cookie returned by the server. Example:

json
[
  {
    "Name": "1P_JAR",
    "Value": "2020-08-30-16",
    "Path": "/",
    "Domain": ".google.com",
    "Expires": "2020-09-29T16:32:11Z",
    // ...
  },
  // ...
]

TIP

Always check IsValid() and StatusCode() before using the response data. Handle errors and unexpected status codes appropriately.

Examples

Example 1: Log response body if successful

ts
var hc = new HttpCli();
var res = hc.Url("https://www.example.com").Timeout(30).Get();
if (res.IsValid() && res.StatusCode() === 200) {
  Log(res.BodyAsString());
} else {
  Log('Request failed: ' + res.StatusCode());
}

Example 2: Save response body to file

ts
var hc = new HttpCli();
var res = hc.Url("https://www.example.com/image.png").Timeout(30).Get();
if (res.IsValid() && res.StatusCode() === 200) {
  if (res.BodySaveToFile('/tmp/image.png')) {
    Log('Image saved successfully.');
  } else {
    Log('Failed to save image.');
  }
} else {
  Log('Request failed: ' + res.StatusCode());
}