HttpRes response object
Every time you call an HttpCli verb method, it returns an HttpRes object containing the response data and metadata.
Example Usage
var hc = new HttpCli();
var res = hc.Url("https://www.example.com").Timeout(30).Get();
// "res" is an HttpRes object with its own methodsThe HttpRes object provides the following methods:
IsValid
res.IsValid(): boolean;Returns true if the HTTP/HTTPS call completed, or false otherwise (e.g., if the call timed out).
StatusCode
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
res.BodyAsString(): string;Returns the response body as a string (useful for web pages, JSON, etc.).
BodyAsBytes
res.BodyAsBytes(): number[];Returns the response body as an array of bytes (useful for binary data, such as images).
BodySaveToFile
res.BodySaveToFile(filePath: string): boolean;Saves the response body to the specified file path. Returns true if successful, false otherwise.
ContentType
res.ContentType(): string;Returns the MIME Content-Type reported by the server.
ContentLength
res.ContentLength(): number;Returns the Content-Length reported by the server (may be missing for some responses).
Encoding
res.Encoding(): string;Returns the Content-Transfer-Encoding reported by the server (may be missing for some responses).
Headers
res.Headers(): object;Returns a JSON object with all response headers as properties. Example:
{
"Cache-Control": "max-age=604800",
"Content-Type": "text/html; charset=UTF-8",
"Date": "Sun, 30 Aug 2020 16:24:06 GMT",
// ...
}Cookies
res.Cookies(): object[];Returns an array of objects, each representing a cookie returned by the server. Example:
[
{
"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
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
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());
}