You are viewing an older version of the site. Click here to view
the latest version of this page. (This may be a dead link, if so, try the root page of the docs
here.)
== http_request ==
url, settings |- ! scope="row" | Throws | [[../objects/ms.lang.FormatException|ms.lang.FormatException]] |- ! scope="row" | Since | 3.3.1 |- ! scope="row" | Restricted |
Copy Code
The output might be:
Copy Code
The output might be:
Copy Code
The output might be:
Makes an HTTP request to the given url.
=== Vital Info ===
{| style="width: 40%;" cellspacing="1" cellpadding="1" border="1" class="wikitable"
|-
! scope="col" width="20%" |
! scope="col" width="80%" |
|-
! scope="row" | Name
| http_request
|-
! scope="row" | Returns
| void
|-
! scope="row" | Usages
| url, callback url, settings |- ! scope="row" | Throws | [[../objects/ms.lang.FormatException|ms.lang.FormatException]] |- ! scope="row" | Since | 3.3.1 |- ! scope="row" | Restricted |
Yes
|-
! scope="row" | Optimizations
| None
|}If the second parameter is a closure, it works the same as giving the closure to
the success parameter in the settings object. The settings object is an array
with the following fields, all of which are optional aside from the complete member.
{{Warning|text=There are a limited number of outgoing "slots" that can be used
at any given time. This method is meant for quick completing requests, not lengthy requests.}}
{| width="100%" cellspacing="1" cellpadding="1" border="1" class="wikitable"
|-
! scope="col" width="6%" | Setting
! scope="col" width="10%" | Type
! scope="col" width="6%" | Default
! scope="col" width="78%" | Description
|-
| method
| string
| null
| One of the following methods: POST, GET, HEAD, OPTIONS, PUT, DELETE, TRACE, PATCH. If null, it will use GET if there are no
params, or POST if there are.
|-
| headers
| array
| null
| Sets the headers for the HTTP request. Depending on if useDefaultHeaders is true or not,
certain headers may be set for you already. The array should be an associative array. The keys
of course will be strings, but the value may either be a string or an array of strings. If the
value is an array of strings, it will be parsed appropriately. If a cookiejar is supplied,
then the cookies will be automatically set in the headers, regardless of the value of the useDefaultHeaders
setting.
|-
| params
| array
| null
| An associative array of parameters to send. If the method is GET, they will be encoded into
the URL, otherwise they will be part request body. If the URL and the params include
the same parameter, the result is undefined. Regardless, the parameters will be encoded properly
when passed in as part of the params object, so it is recommended to use this always, especially
if dealing with user input or other possibly unescaped content. The subtype of the array may be any
primitive or an array of primitives. Sub arrays are encoded properly. If params is a string, it is
assumed to be raw body data, and added literally to the request body, as is. If the parameter is
a byte_array, that is also encoded exactly as is. The Content-Type header is not set
for you if this occurs, and will likely need to be set manually. The HTTP/1.1 specification specifically
notes that servers should ignore the request body for certain methods (i.e. GET), but in practice,
many servers expect this, and so while it is against the standard, this method still allows it.
|-
| cookiejar
| array
| null
| An array of cookies. If the parameter is null, then cookies will not be managed at all by this
function, but if the array is empty (or already contains some cookies) then the cookies will be
managed automatically. If you intend on using cookies, it is strongly recommended that you allow
this system to automatically parse the cookies from the responses and set the cookies in the cookie
jar, as there are many security flaws that can be introduced with a poor cookie manager implementation,
and care has been taken to implement this correctly. Regardless, each cookie will be an array with the
following fields set:
* string domain - The domain under which this cookie applies
* string name - The name of this cookie
* string value - The value of this cookie
* string path - The path under which this cookie applies in the domain
* int expiration - When the cookie expires. 0 means it never expires, because it is a session cookie. \
The function will not send expired cookies, and will remove them from the cookie jar automatically. \
Session cookies cannot technically expire, and must be removed manually by you, if you are storing cookies \
for a long period of time.
* boolean httpOnly - If true, this cookie shouldn't be provided to clients. In practice, this isn't very useful however.
* boolean secureOnly - If true, this cookie only applies in https, not http.
|-
| followRedirects
| boolean
| true
| If true, the system will automatically follow 3xx series redirect codes, and will then access the resulting
page, instead of simply returning at that point. The default is true, because more often than not, you shouldn't
care if a page redirects a few times first, and only want the resulting page.
|-
| success
| closure
| required parameter
| This is the only required parameter. When the request finishes on the background thread, it the resulting HTTP
response is returned to this closure. The closure should accept 1 parameter, which will be the HTTP response object,
which contains the following fields:
* string body - The string body content of the response. This is usually the only thing of interest in the response. \
This will not be present if binary was true.
* byte_array data - The binary content of the response. This will only be present if binary was true.
* array headers - An associative array of arrays of the returned headers. \
Often times headers are not repeated, so @response['headers']['Server'][0] for instance will be acceptable. \
Headers are not usually needed for non-referencial purposes anyways.
* int responseCode - The response code of the request, for instance 404 for pages that aren't found.
* int responseText - The response text of the request, for instance "Not Found" for a 404
* string httpVersion - The HTTP version the server is using, for instance "1.1"
* boolean error - This bit is set to true if a 4xx or 5xx response code was received.
Note that it is considered a success even if the request results in a non 200 response, the error
handler is only called if the connection fails entirely, and no response could be retrieved from the server.
To check if the HTTP response is a considered an error response, you can check the error bit, or check the responseCode
yourself.
|-
| error
| closure
| null
| If the request fails for whatever reason, this receives the exception generated. By default, the exception
is logged using the default uncaught exception handler.
|-
| timeout
| int
| 60000
| Sets the timeout that the background thread will wait for before giving up. 0 means no timeout, though this
isn't recommended, because this could cause future calls to http_request to fail, because there is a limited number
of web requests that can be running concurrently.
|-
| username
| string
| null
| Sets the username to use in response to basic HTTP authentication challenges.
|-
| password
| string
| null
| Sets the password to use in response to basic HTTP authentication challenges.
|-
| useDefaultHeaders
| boolean
| true
| Automatically adds the default headers to this request, unless specifically overridden. Note that some headers
simply cannot be overridden, for instance Host and User-Agent will ALWAYS be set. The default headers are:
{Accept=text/*, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8, User-Agent=Java/1.8.0_292/MethodScript, Connection=close, Accept-Encoding=br, deflate, identity, gzip, DNT=1}
|-
| trustStore
| boolean or array
| null
| If value is null, then the default JVM behavior is used. If trustStore is false, then no trust store will be used,
and all certificates will be trusted when making https connections (NOTE: this is generally dangerous. Instead, you
should use specific overrides, by providing an array). If the value is an array, it is assumed to be an array of fingerprints: hash
mechanism, for instance: array('02 79 AB D6 97 19 A2 CB E8 79 11 B2 7F AF 8D': 'SHA-256'). The spaces in the fingerprint
are optional. The JVM's trust store is used in addition to the provided fingerprints, so already valid certificates
do not need to be listed here. If you wish to disable the JVM's store, and only use the provided certificates, then
you can send exactly the key/value pair ('no default': 'no default') as a value inside of the array, and the default JVM certificates will be
ignored. When providing fingerprints, only the highest security scheme should be provided (don't provide a SHA-1
fingerprint if a SHA-256 one is available). If multiple fingerprints for the same certificate are provided, then
they will be resolved top to bottom. When using the default trust store, the certificate is first checked with the
built in trust store, and then only if it fails is custom store checked. This prevents you from having to update
your custom trust store if the certificate is later changed to a valid certificate. It is not required that you
provide the leaf certificate. If a parent certificate is provided, then the whole certificate chain is considered
trusted.
|-
| download
| string
| null
| If this is not null, the file will be downloaded instead of returned, and saved to the specified location on
disk. The contents are saved to disk as is, so the value of binary is not relevant, and is ignored.
Note that this is currently only enabled from cmdline mode, but will be added in general at a later date.
If this setting is set from non-cdmline mode, it is silently ignored.
|-
| downloadStrategy
| FileWriteMode
| SAFE_WRITE
| If download is set, then this is the download strategy that will be used. OVERWRITE, APPEND, or SAFE_WRITE.
|-
| textEncoding
| string
| UTF-8
| If binary is false, then this is the character encoding to assume.
|-
| binary
| boolean
| false
| If true, a byte_array of the content is returned, instead of a string. If false, then the textEncoding parameter
decides on the encoding format to use.
|-
| blocking
| boolean
| false
| If this is true, the method will block until it is complete, and it also won't use the internal thread pool.
|-
| log
| boolean
| false
| When initially writing code, it may be useful to get explicit debug information printed out. If this
is set to true, then detailed debug information will be printed to console.
|}
The most basic usage is to get the html of the google homepage, not worrying about cookies
or anything complicated. That code is very straightforward:
Copy Code
The settings can adjust the more complicated options needed to do more complex tasks, but for
most basic needs, the usage is very straightforward. One thing you may more commonly find yourself needing
is cookie support. Cookies are managed by default by the framework, though you must provide a "cookie jar"
for it to use. The cookie is just an array which you give it, it can be empty at first, or you
can add cookies manually, if you know exactly what you're doing. After a "session" you can either
throw out all the cookies, or use http_clear_session_cookies on the cookie jar object, which will clear
the appropriate cookies for you. You may keep as many separate cookie jars as you like, and each is
considered a separate "session".
A FormatException will be thrown by the function itself if the URL is malformed.
=== Usages ===
http_request('http://www.google.com', closure(@response){
msg(@response['body']);
});

1 {{function|http_request}}('http://www.google.com', {{keyword|closure}}(@response){
2 {{function|msg}}(@response['body']);
3 });
http_request(url, callback)
http_request(url, settings)=== Examples === ====Example 1==== Getting headers from a website Given the following code:
http_request('http://www.google.com', array(
success: closure(@response,
msg(@response['headers']['Server'][0]);
)
));

1 {{function|http_request}}('http://www.google.com', {{function|array}}(
2 success: {{keyword|closure}}(@response,
3 {{function|msg}}(@response['headers']['Server'][0]);
4 )
5 ));
gws====Example 2==== Using a cookie jar Given the following code:
@cookiejar = array()
http_request('http://www.google.com', array(
cookiejar: @cookiejar, success: closure(@resp) {
msg(@cookiejar);
}
));

1 @cookiejar = {{function|array}}()
2 {{function|http_request}}('http://www.google.com', {{function|array}}(
3 cookiejar: @cookiejar, success: {{keyword|closure}}(@resp) {
4 {{function|msg}}(@cookiejar);
5 }
6 ));
<cookie jar would now have cookies in it>====Example 3==== Sending some json to the server Given the following code:
http_request('http://example.com', array(
method: 'POST',
headers: array(
// The content type isn't set automatically if we send a string via params,
// so we have to set this manually to application/json here, since we're sending
// json data. Other data types may have different MIME types.
'Content-Type': 'application/json'
), params: json_encode(array(
'arg1': 'value',
'arg2': 'value',
)),
success: closure(@response){
// Handle the server's response
}));

01 {{function|http_request}}('http://example.com', {{function|array}}(
02 method: 'POST',
03 headers: {{function|array}}(
04 // The content type isn't set automatically if we send a string via params,
05
06 // so we have to set this manually to application/json here, since we're sending
07
08 // json data. Other data types may have different MIME types.
09
10 'Content-Type': 'application/json'
11 ), params: {{function|json_encode}}({{function|array}}(
12 'arg1': 'value',
13 'arg2': 'value',
14 )),
15 success: {{keyword|closure}}(@response){
16 // Handle the server's response
17
18 }));
<A POST request with json data would be sent to the server>===See Also===
[[API/functions/http_clear_session_cookies.html|http_clear_session_cookies]]
Find a bug in this page? Edit this page yourself, then submit a pull request. (Note this page is automatically generated from the documentation in the source code.)