http

October 22, 2022

http

Stability: 2-Stable

The http module provides some functions for making http requests.

http.get(url[, options, callback])

  • url {string} The requested URL address must start with "http://" or "https://". If the url does not start with "http://", it will default to "http://".
  • options {Object} Request options. See [http.request()][].
  • callback {Function} Callback function, optional, its parameter is a [Response][] object. If no callback function is added, the request will be blocked and executed synchronously.

Make an HTTP GET request to the address url. If there is no callback function, the response to this request will be returned when the request is completed or failed (see [Response][]).

The simplest GET request is as follows:

console.show();
var r = http.get("www.baidu.com");
log("code = "+ r.statusCode);
log("html = "+ r.body.string());

The GET request in the form of callback is as follows:

console.show();
http.get("www.baidu.com", {}, function(res, err){
if(err){
console.error(err);
return;
}
log("code = "+ res.statusCode);
log("html = "+ res.body.string());
});

If you want to add HTTP header information, add it to the options parameter, for example:

console.show();
var r = http.get("www.baidu.com", {
headers: {
'Accept-Language':'zh-cn,zh;q=0.5',
'User-Agent':'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
}
});
log("code = "+ r.statusCode);
log("html = "+ r.body.string());

An example of requesting weather and parsing the returned weather JSON result is as follows:

var city = "101010100";
var res = http.get("http://t.weather.itboy.net/api/weather/city/" + city);
if(res.statusCode != 200){
console.log("Request failed: "+ res.statusCode +" "+ res.statusMessage);
}else{
var weather = res.body.json();
log(weather);
console.log(util.format("Temperature: %s Humidity: %s Air Quality: %s", weather.data.wendu,
weather.data.shidu, weather.data.quality));
}

http.post(url, data[, options, callback])

  • url {string} The requested URL address must start with "http://" or "https://". If the url does not start with "http://", it will default to "http://".
  • data {string} | {Object} POST data.
  • options {Object} Request options.
  • callback {Function} Callback, its parameter is a [Response][] object. If the callback parameter is not added, the request will be blocked and executed synchronously.

Make an HTTP POST request to the address url. If there is no callback function, the response to this request will be returned when the request is completed or failed (see [Response][]).

The POST data can be a string or a key-value pair. The specific meaning depends on the value of options.contentType. The default is "application/x-www-form-urlencoded" (form submission), which is the default method of JQuery's ajax function.

An example of a simulated form submission to log in to Taobao is as follows:

var url = "https://login.taobao.com/member/login.jhtml";
var username = "your username";
var password = "Your password";
var res = http.post(url, {
"TPL_username": username,
"TPL_password": password
});
var html = res.body.string();
if(html.indexOf("Page Jumping") != -1){
toastLog("Login successful");
}else{
toastLog("Login failed");
}

http.postJson(url[, data, options, callback])

  • url {string} The requested URL address must start with "http://" or "https://". If the url does not start with "http://", it will default to "http://".
  • data {Object} POST data.
  • options {Object} Request options.
  • callback {Function} Callback, its parameter is a [Response][] object. If the callback parameter is not added, the request will be blocked and executed synchronously.

Initiate a POST request to the target Url in JSON format. If there is no callback function, the response to this request will be returned when the request is completed or failed (see [Response][]).

The JSON format means that JSON.stringify() will be called to convert the data object into a JSON string, and the "Content-Type" attribute is set to "application/json" in the HTTP header information. This method is the default method of AngularJS's ajax function.

An example of calling the Turing robot interface is as follows:

var url = "http://www.tuling123.com/openapi/api";
r = http.postJson(url, {
    key: "65458a5df537443b89b31f1c03202a80",
    info: "Hello",
    userid: "1",
});
toastLog(r.body.string());

http.postMultipart(url, files[, options, callback])

  • url {string} The requested URL address must start with "http://" or "https://". If the url does not start with "http://", it will default to "http://".
  • files {Object} POST data.
  • options {Object} Request options.
  • callback {Function} Callback, its parameter is a Response object. If the callback parameter is not added, the request will be blocked and executed synchronously.

Initiate a multipart/form-data request to the target address (usually used for file uploads, etc.), where the files parameter is a key-value pair of {name1: value1, name2: value2, ...}, and the value format can be as follows Several situations:

  1. string
  2. File type, that is, the type returned by open()
  3. [fileName, filePath]
  4. [fileName, mimeType, filePath]

Among them, 1 is a non-file parameter, and 2, 3, and 4 are file parameters. For example, the simplest file upload request is:

var res = http.postMultipart(url, {
file: open("/sdcard/1.txt")
});
log(res.body.string());

If format 2 is used, the code is

var res = http.postMultipart(url, {
file: ["1.txt", "/sdcard/1.txt"]
});
log(res.body.string());

If format 3 is used, the code is

var res = http.postMultipart(url, {
file: ["1.txt", "text/plain", "/sdcard/1.txt"]
});
log(res.body.string());

If format 2 is used with non-file parameter "appId=test", it is:

var res = http.postMultipart(url, {
appId: "test",
file: open("/sdcard/1.txt")
});
log(res.body.string());

http.request(url[, options, callback])

  • url {string} The requested URL address must start with "http://" or "https://". If the url does not start with "http://", it will default to "http://".
  • options {Object} Request options. See [http.buildRequest()][].
  • callback {Function} Callback, its parameter is a [Response][] object. If the callback parameter is not added, the request will be blocked and executed synchronously.

Initiate an HTTP request to the target address url. If there is no callback function, the response to this request will be returned when the request is completed or failed (see [Response][]).

Options can contain the following attributes:

  • headers {Object} HTTP header information in the form of key-value pairs. For HTTP header information, see Novice Tutorial: HTTP Response Header Informationopen in new window.
  • method {string} HTTP request method. Including "GET", "POST", "PUT", "DELETE", "PATCH".
  • contentType {string} The "Content-Type" in the HTTP header information indicates the content type of the HTTP request. For example, "text/plain", "application/json". For more information, see Novice Tutorial: HTTP contentTypeopen in new window.
  • body {string} | {Array} | {Function} The content of the HTTP request. It can be a string or a byte array; or it can be a [BufferedSink](https://github.com/square/okio/blob/master/okio/src/main/java/okio/BufferedSink. java) is a function with parameters.

This function is the basic function of get, post, postJson and other functions. Therefore, unless it is a request such as PUT, DELETE, or a more customized HTTP request, it will be more convenient to directly use functions such as get, post, postJson.

Response

The response to the HTTP request.

Response.statusCode

  • {number}Status code. For example, 200 (OK), 404 (Not Found), etc.

For information about HTTP status codes, see Rookie Tutorial: HTTP Status Codesopen in new window.

Response.statusMessage

  • {string}

HTTP status information of the current response. For example, "OK", "Bad Request", "Forbidden".

For information about HTTP status codes, see Rookie Tutorial: HTTP Status Codesopen in new window.

example:

var res = http.get("www.baidu.com");
if(res.statusCode >= 200 && res.statusCode <300){
toast("The page is successfully obtained!");
}else if(res.statusCode == 404){
toast("The page was not found...");
}else{
toast("error: "+ res.statusCode +" "+ res.statusMessage);
}

Response.headers

  • {Object}

The HTTP header information of the current response. The key of this object is the response header name, and the value is the respective response header value. All response header names are lowercase (?).

For HTTP header information, see Novice Tutorial: HTTP Response Header Informationopen in new window.

example:

console.show();
var res = http.get("www.qq.com");
console.log("HTTP Headers:")
for(var headerName in res.headers){
console.log("%s: %s", headerName, res.headers[headerName]);
}

Response.body

  • {Object}

The content of the current response. He has the following attributes and functions:

  • bytes() {Array} returns the response content as a byte array
  • string() {string} returns the response content as a string
  • json() {Object} Treat the response content as data in JSON format and call JSON.parse to return the parsed object
  • contentType {string} The content type of the current response

Response.request

  • {Request} The request corresponding to the current response. See [Request][].

Response.url

  • {number} The request URL corresponding to the current response.

Response.method

  • {string} The method of the HTTP request corresponding to the current response. For example, "GET", "POST", "PUT", etc.

HTTP status of the current response

Last update:
Contributors: Bruce