http
Stability: 2 - Stable
The http module provides helper functions for making HTTP requests.
The http module provides helper functions for making HTTP requests.
http.get(url[, options, callback])
url{string} URL to request. It should start with"http://"or"https://". If not,"http://"is assumed.options{Object} Request options. See [http.request()][].callback{Function} Optional callback. Receives a [Response][] object. If omitted, the request runs synchronously (blocking).
Performs an HTTP GET request to url. If no callback is provided, it returns the response when the request finishes (or throws on error). See [Response][].
The simplest GET request:
console.show();
var r = http.get("www.baidu.com");
log("code = " + r.statusCode);
log("html = " + r.body.string());GET request using a callback:
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());
});To add HTTP headers, put them in options.headers, 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());Example: request weather data and parse the returned JSON:
var city = "Guangzhou";
var res = http.get(
"http://www.sojson.com/open/api/weather/json.shtml?city=" + city,
);
if (res.statusCode != 200) {
toast("Request failed: " + res.statusCode + " " + res.statusMessage);
} else {
var weather = res.body.json();
log(weather);
toast(
util.format(
"Temp: %s Humidity: %s Air quality: %s",
weather.data.wendu,
weather.data.shidu,
weather.quality,
),
);
}http.post(url, data[, options, callback])
url{string} URL to request. It should start with"http://"or"https://". If not,"http://"is assumed.data{string} | {Object} POST body.options{Object} Request options.callback{Function} Optional callback. Receives a [Response][] object. If omitted, the request runs synchronously (blocking).
Performs an HTTP POST request to url. If no callback is provided, it returns the response when the request finishes. See [Response][].
The POST body can be a string or an object of key-value pairs. The actual meaning depends on options.contentType. The default is "application/x-www-form-urlencoded" (form submit), which matches jQuery Ajax defaults.
Example: simulate a form POST:
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.contains("Redirecting")) {
toast("Login success");
} else {
toast("Login failed");
}http.postJson(url[, data, options, callback])
url{string} URL to request. It should start with"http://"or"https://". If not,"http://"is assumed.data{Object} POST body.options{Object} Request options.callback{Function} Optional callback. Receives a [Response][] object. If omitted, the request runs synchronously (blocking).
Performs an HTTP POST request with a JSON body. If no callback is provided, it returns the response when the request finishes. See [Response][].
“JSON body” means it will call JSON.stringify() on data and set Content-Type to "application/json". This matches AngularJS Ajax defaults.
Example:
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} URL to request. It should start with"http://"or"https://". If not,"http://"is assumed.files{Object} Form fields and files payload.options{Object} Request options.callback{Function} Optional callback. Receives aResponse. If omitted, the request runs synchronously (blocking).
Performs a multipart/form-data request (typically for file uploads). The files argument is a key-value object like {name1: value1, name2: value2, ...}. The value can be:
string- A file handle (the value returned by
open()) - [fileName, filePath]
- [fileName, mimeType, filePath]
Type 1 is a non-file field, and 2/3/4 represent file fields. Example (simplest upload):
var res = http.postMultipart(url, {
file: open("/sdcard/1.txt"),
});
log(res.body.string());If using type 3:
var res = http.postMultipart(url, {
file: ["1.txt", "/sdcard/1.txt"],
});
log(res.body.string());If using type 4:
var res = http.postMultipart(url, {
file: ["1.txt", "text/plain", "/sdcard/1.txt"],
});
log(res.body.string());If you also want to include a non-file field like appId=test:
var res = http.postMultipart(url, {
appId: "test",
file: open("/sdcard/1.txt"),
});
log(res.body.string());http.request(url[, options, callback])
url{string} URL to request. It should start with"http://"or"https://". If not,"http://"is assumed.options{Object} Request options. See [http.buildRequest()][].callback{Function} Optional callback. Receives a [Response][] object. If omitted, the request runs synchronously (blocking).
Performs a low-level HTTP request to url. If no callback is provided, it returns the response when the request finishes. See [Response][].
options can include the following fields:
headers{Object} HTTP headers as key-value pairs. See: Runoob: HTTP header fields.method{string} HTTP method, e.g."GET","POST","PUT","DELETE","PATCH".contentType{string} The"Content-Type"header value, e.g."text/plain","application/json". See: Runoob: HTTP content type.body{string} | {Array} | {Function} Request body. Can be a string, a byte array, or a function that writes to a BufferedSink.
This is the underlying primitive used by get, post, postJson, etc. Unless you need methods like PUT/DELETE or advanced customization, using get / post / postJson is usually easier.
http.buildRequest(url, options)
url{string} Request URL.options{Object} Request options. It is recommended to pass it explicitly (at least{}).- Returns {Request}
Builds a low-level Request object, typically used together with http.client() or the underlying http.__okhttp__ chain.
// Tip: pass at least an empty options object to avoid errors
let req1 = http.buildRequest("https://example.com", {});
log(req1);
let req2 = http.buildRequest("https://example.com", {
method: "GET",
headers: {
"User-Agent": "AutoJsPro",
},
});
log(req2);http.client()
- Returns {okhttp3.OkHttpClient}
Returns the underlying OkHttpClient instance used by the http module.
let client = http.client();
let request = http.buildRequest("https://pro.autojs.run", { method: "GET" });
let response = client.newCall(request).execute();
log(response);http.okhttp
- {com.stardust.autojs.core.http.MutableOkHttp}
The mutable OkHttp wrapper used by the http module for advanced network configuration (timeouts, retries, etc.).
Tip: this is an advanced interface. For most scripts, prefer
http.get/post/postJson/postMultipart/request.
http.__okhttp__.getTimeout()
- Returns {long}
Gets the current timeout (milliseconds).
log(http.__okhttp__.getTimeout());http.__okhttp__.setTimeout(timeout)
timeout{long} Timeout (milliseconds)
Sets the current timeout configuration.
let oldTimeout = http.__okhttp__.getTimeout();
http.__okhttp__.setTimeout(30000);
log(http.__okhttp__.getTimeout());
http.__okhttp__.setTimeout(oldTimeout); // recommended to restorehttp.__okhttp__.getMaxRetries()
- Returns {int}
Gets the current max retry count.
log(http.__okhttp__.getMaxRetries());http.__okhttp__.setMaxRetries(count)
count{int} Max retries
Sets the max retry count.
let oldRetries = http.__okhttp__.getMaxRetries();
http.__okhttp__.setMaxRetries(3);
log(http.__okhttp__.getMaxRetries());
http.__okhttp__.setMaxRetries(oldRetries); // recommended to restorehttp.__okhttp__.client()
- Returns {okhttp3.OkHttpClient}
Returns the underlying OkHttpClient instance.
let c = http.__okhttp__.client();
log(c);http.__okhttp__.connectTimeoutMillis()
- Returns {int}
Returns connect timeout (milliseconds).
log(http.__okhttp__.connectTimeoutMillis());http.__okhttp__.readTimeoutMillis()
- Returns {int}
Returns read timeout (milliseconds).
log(http.__okhttp__.readTimeoutMillis());http.__okhttp__.writeTimeoutMillis()
- Returns {int}
Returns write timeout (milliseconds).
log(http.__okhttp__.writeTimeoutMillis());http.__okhttp__.pingIntervalMillis()
- Returns {int}
Returns ping interval (milliseconds).
log(http.__okhttp__.pingIntervalMillis());http.__okhttp__.followRedirects()
- Returns {boolean}
Returns whether redirects are followed.
log(http.__okhttp__.followRedirects());http.__okhttp__.followSslRedirects()
- Returns {boolean}
Returns whether HTTPS redirects are followed.
log(http.__okhttp__.followSslRedirects());http.__okhttp__.retryOnConnectionFailure()
- Returns {boolean}
Returns whether retry-on-connection-failure is enabled.
log(http.__okhttp__.retryOnConnectionFailure());http.__okhttp__.newBuilder()
- Returns {okhttp3.OkHttpClient.Builder}
Returns an OkHttp Builder for further configuration.
let builder = http.__okhttp__.newBuilder();
log(builder);http.__okhttp__.newCall(request)
request{okhttp3.Request} Request object- Returns {okhttp3.Call}
Creates an executable call object using the underlying client.
let req = http.buildRequest("https://example.com", { method: "GET" });
let call = http.__okhttp__.newCall(req);
log(call);http.__okhttp__.newWebSocket(request, listener)
request{okhttp3.Request} WebSocket requestlistener{okhttp3.WebSocketListener} WebSocket listener- Returns {okhttp3.WebSocket}
Creates a WebSocket connection.
// Signature only. listener should be a WebSocketListener instance.
// let ws = http.__okhttp__.newWebSocket(request, listener);http.__okhttp__.newClient(builder)
builder{okhttp3.OkHttpClient.Builder} Client builder- Returns {okhttp3.OkHttpClient}
Creates a new OkHttpClient from the given builder.
let builder = http.__okhttp__.newBuilder();
let newClient = http.__okhttp__.newClient(builder);
log(newClient);http.__okhttp__.muteClient()
- Returns {void}
Applies current underlying configuration to the client silently.
http.__okhttp__.muteClient();http.__okhttp__.muteClient(builder)
builder{okhttp3.OkHttpClient.Builder}- Returns {void}
Writes current underlying configuration into the specified builder.
let builder = http.__okhttp__.newBuilder();
http.__okhttp__.muteClient(builder);http.__okhttp__.interceptors()
- Returns {java.util.List}
Returns the interceptors list.
log(http.__okhttp__.interceptors());http.__okhttp__.networkInterceptors()
- Returns {java.util.List}
Returns the network interceptors list.
log(http.__okhttp__.networkInterceptors());http.__okhttp__.protocols()
- Returns {java.util.List}
Returns the currently enabled protocol list.
log(http.__okhttp__.protocols());http.__okhttp__.dispatcher()
- Returns {okhttp3.Dispatcher}
Returns the underlying request dispatcher.
log(http.__okhttp__.dispatcher());http.__okhttp__.connectionPool()
- Returns {okhttp3.ConnectionPool}
Returns the connection pool.
log(http.__okhttp__.connectionPool());http.__okhttp__.proxy()
- Returns {java.net.Proxy}
Return current proxy configuration.
log(http.__okhttp__.proxy());http.__okhttp__.proxySelector()
- Returns {java.net.ProxySelector}
Return proxy selector.
log(http.__okhttp__.proxySelector());http.__okhttp__.proxyAuthenticator()
- Returns {okhttp3.Authenticator}
Return proxy authenticator.
log(http.__okhttp__.proxyAuthenticator());http.__okhttp__.authenticator()
- Returns {okhttp3.Authenticator}
Return authenticator.
log(http.__okhttp__.authenticator());http.__okhttp__.dns()
- Returns {okhttp3.Dns}
Return DNS configuration object.
log(http.__okhttp__.dns());http.__okhttp__.cookieJar()
- Returns {okhttp3.CookieJar}
Return cookie jar.
log(http.__okhttp__.cookieJar());http.__okhttp__.cache()
- Returns {okhttp3.Cache}
Return cache.
log(http.__okhttp__.cache());http.__okhttp__.internalCache()
- Returns {okhttp3.internal.cache.InternalCache}
Return internal cache.
log(http.__okhttp__.internalCache());http.__okhttp__.hostnameVerifier()
- Returns {javax.net.ssl.HostnameVerifier}
Return hostname verifier.
log(http.__okhttp__.hostnameVerifier());http.__okhttp__.sslSocketFactory()
- Returns {javax.net.ssl.SSLSocketFactory}
Return SSL socket factory.
log(http.__okhttp__.sslSocketFactory());http.__okhttp__.socketFactory()
- Returns {javax.net.SocketFactory}
Return socket factory.
log(http.__okhttp__.socketFactory());http.__okhttp__.certificatePinner()
- Returns {okhttp3.CertificatePinner}
Return certificate pinner config.
log(http.__okhttp__.certificatePinner());http.__okhttp__.eventListenerFactory()
- Returns {okhttp3.EventListener.Factory}
Return event listener factory.
log(http.__okhttp__.eventListenerFactory());http.__okhttp__.connectionSpecs()
- Returns {java.util.List}
Return connection specs list.
log(http.__okhttp__.connectionSpecs());http.okhttp common properties
http.__okhttp__.timeout{number} Current timeout in milliseconds (shortcut)http.__okhttp__.maxRetries{number} Current max retries (shortcut)http.__okhttp__.connectTimeout{number} Current connect timeout in milliseconds (shortcut)http.__okhttp__.readTimeout{number} Current read timeout in milliseconds (shortcut)http.__okhttp__.writeTimeout{number} Current write timeout in milliseconds (shortcut)http.__okhttp__.pingInterval{number} Current ping interval in milliseconds (shortcut)http.__okhttp__.certificateChainCleaner{Object} Certificate chain cleaner objecthttp.__okhttp__.class{Object} Current Java class object
log(http.__okhttp__.timeout, http.__okhttp__.maxRetries);
log(http.__okhttp__.certificateChainCleaner, http.__okhttp__.class);Response
HTTP response.
Response.statusCode
- {number}
HTTP status code. For example: 200 (OK), 404 (Not Found), etc.
See: Runoob: HTTP status codes.
Response.statusMessage
- {string}
HTTP status message. For example: "OK", "Bad Request", "Forbidden".
See: Runoob: HTTP status codes.
Example:
var res = http.get("www.baidu.com");
if (res.statusCode >= 200 && res.statusCode < 300) {
toast("Page loaded");
} else if (res.statusCode == 404) {
toast("Page not found");
} else {
toast("Error: " + res.statusCode + " " + res.statusMessage);
}Response.headers
- {Object}
Response headers. Keys are header names, values are header values. All header names are lowercased.
See: Runoob: HTTP header fields.
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}
Response body. It has the following methods/properties:
- bytes() {Array} Return response body as a byte array
- string() {string} Return response body as a string
- json() {Object} Parse response body as JSON via
JSON.parse()and return the object - contentType {string} Response content type
Response.request
- {Request} Request for this response. See [Request][].
Response.url
- {number} Request URL for this response.
Response.method
- {string} HTTP method of the request, e.g. "GET", "POST", "PUT".
