Copy of roUrlTransfer (DOCS-1198)

ON THIS PAGE


This object is used for reading from and writing to remote servers through URLs. It reports transfer status using the roUrlEvent object. The JavaScript equivalent is http.

Object Creation: This object is created with no parameters.

CreateObject("roUrlTransfer")

Note

You must create a separate roUrlTransfer instance for each asset you wish to read/write.

ifUserData

SetUserData(user_data As Object)

Sets the user data that will be returned when events are raised.

GetUserData() As Object

Returns the user data that has previously been set via SetUserData(). It will return Invalid if no data has been set.

ifIdentity

GetIdentity() As Integer

Returns a unique number that can be used to identify when events originate from this object.

Note

The ifIdentity interface has been deprecated. We recommend using the ifUserData interface instead.

ifMessagePort

SetPort(port As roMessagePort) As Void

Sets the message port to which events will be posted for asynchronous requests.

ifUrlTransfer

SetUrl(URL As String) As Boolean

Sets the URL for the transfer request. This function returns False on failure. Use GetFailureReason to learn the reason for the failure.

AddHeader(name As String, value As String) As Boolean

Adds the specified HTTP header. This is only valid for HTTP URLs. This function returns False on failure. Use GetFailureReason() to learn the reason for the failure.

GetToString() As String

Connects to the remote service as specified in the URL and returns the response body as a string. This function cannot return until the exchange is complete, and it may block for a long time. Having a single string return means that much of the information (headers, response codes) has been discarded. If you need this information, you can use AsyncGetToString() instead.

The size of the returned string is limited to 65,536 characters.

GetToFile(filename As String) As Integer

Connects to the remote service as specified in the URL and writes the response body to the specified file. This function does not return until the exchange is complete and may block for a long time. The response code from the server is returned. It is not possible to access any of the response headers. If you need this information, use AsyncGetToFile() instead.

AsyncGetToString() As Boolean

Begins a GET request to a string asynchronously. Events will be sent to the message port associated with the object. If False is returned, then the request could not be issued and no events will be delivered.

AsyncGetToFile(filename As String) As Boolean

Begins a GET request to a file asynchronously. Events will be sent to the message port associated with the object. If False is returned, then the request could not be issued and no events will be delivered.

EnableResume(enable As Boolean) As Boolean

Specifies the file-creation behavior of the GetToFile() and ASyncGetToFile() methods. If this method is set to False (the default setting), each download will generate a temporary file: if the download is successful, the temporary file will be renamed to the specified filename; if the download fails, the temporary file will be deleted. If this method is set to True, the file with the specified filename will be created regardless of whether the download is successful or not—this allows the download to be resumed by a subsequent GetToFile() or ASyncGetToFile() call.

Head() As Object

Synchronously perform an HTTP HEAD request and return the resulting response code and headers through an roUrlEvent object. In the event of catastrophic failure (e.g. an asynchronous operation is already active), a null object is returned.

AsyncHead() As Boolean

Begins an ansynchronous HTTP HEAD request. Events will be sent to the message port associated with the object. If the request could not be issued, the method will return False and will not deliver any events.

PostFromString(request As String) As Integer

Uses the HTTP POST method to post the supplied string to the current URL and return the response code. Any response body is discarded.

PostFromFile(filename As String) As Integer

Uses the HTTP POST method to post the contents of the specified file to the current URL and then return the response code. Any response body is discarded.

AsyncPostFromString(request As String) As Boolean

Uses the HTTP POST method to post the supplied string to the current URL. Events of type roUrlEvent will be sent to the message port associated with the object. A False return indicates that the request could not be issued and no events will be delivered.

AsyncPostFromFile(filename As String) As Boolean

Uses the HTTP POST method to post the contents of the specified file to the current URL. Events of the type roUrlEvent will be sent to the message port associated with the object A False return indicates that the request could not be issued and no events will be delivered.

SetUserAndPassword(user As String, password As String) As Boolean

Enables HTTP authentication using the specified user name and password. Note that HTTP basic authentication is deliberately disabled due to it being inherently insecure. HTTP digest authentication is supported.

SetMaximumReceiveBytesPerSecond(bytes_per_second as Double) As Boolean

Limits the rate at which downloads are performed by the roUrlTransfer instance. The source data rate isn't under the direct control of the BrightSign player, but download rates should average below the specified value over time. 

This method returns true on success and false on failure. In event of failure, the GetFailureReason() method may provide more information.

SetMaximumSendBytesPerSecond(bytes_per_second as Double) As Boolean

Limits the rate at which uploads are performed by the roUrlTransfer instance.

This method returns true on success and false on failure. In event of failure, the GetFailureReason() method may provide more information.

SetMinimumTransferRate(bytes_per_second As Integer, period_in_seconds As Integer) As Boolean

Causes the transfer to be terminated if the rate drops below bytes_per_second when averaged over  period_in_seconds. Note that if the transfer is over the Internet, you may not want to set period_in_seconds to a small number in case network problems cause temporary drops in performance. For large file transfers and a small bytes_per_second limit, averaging fifteen minutes or more might be appropriate.

GetFailureReason() As String

May provide additional information if any of the roUrlTransfer methods indicate failure.

SetHeaders(a As Object) As Boolean
 
AsyncGetToObject(type As String) As Boolean

Begins an asynchronious GET request and uses the contents to create an object of the specified type. Events will be sent to the message port associated with the object. If this method returns False, the request could not be issued and no events will be delievered. Only supported types are roSyncSpec and roXMLElement.

AsyncCancel() As Boolean

Cancles any outstanding async requests on the roURLEvent object. 

RetainBodyOnError(retain as Boolean) as Boolean

Specifies whether to return the response body when there is an HTTP error response code. If retain is true, roUrlTransfer provides the body and headers of the response even if the HTTP status code indicates that an error occurred (e.g. a 4x or 5xx status code). If retain is false, roUrlTransfer does not provide the body and headers of the response if the HTTP status code indicates that an error occurred. This method returns True on success, and False if it fails. The default behavior of roUrlTransfer  is equivalent to passing False into the method. 

Note

If RetainBodyOnError() returns as False, call GetFailureReason() to get details. 

EnableUnsafeAuthentication(enable As Boolean) As Boolean

Supports basic HTTP authentication if True. HTTP authentication uses an insecure protocol, which might allow others to easily determine the password. The roUrlTransfer object will still prefer the stronger digest HTTP if it is supported by the server. If this method is False (which is the default setting), it will refuse to provide passwords via basic HTTP authentication, and any requests requiring this authentication will fail.

EnableUnsafeProxyAuthentication(enable As Boolean) As Boolean

Supports basic HTTP authentication against proxies if True (which, unlike EnableUnsafeAuthentication(), is the default setting). HTTP authentication uses an insecure protocol, which might allow others to easily determine the password. If this method is False, it will refuse to provide passwords via basic HTTP authentication, and any requests requiring this authentication type will fail.

EnablePeerVerification(verification As Boolean) As Boolean

Enables checking of TLS/SSL certificates. This method is set to true by default. Disabling peer verficiation allows you to bypass an expired certificate check.

EnableHostVerification(verification As Boolean) As Boolean

Enables checking of the TLS/SSL certificate for the correct hostname. This method is set to true by default. Disabling host verification allows you to accept a certificate being sent for the wrong hostname.

Important

Peer verficiation and host verification are important security checks that prevent "man-in-the-middle" attacks. These features should only be disabled after careful consideration of the security implications.

SetCertificatesFile(filename As String) As Boolean

Configures an alternative set of CA certificates for the connection. This method is useful if the connection certificates are signed by a CA that is not on the the default trusted list (for example, if your organization uses a private CA hierarchy that is not signed by a well known root CA). This method replaces the default list, so the passed certificate file must contain all acceptable CA certificates required for the connection. 

SetClientCertificate(parameters As roAssociativeArray) As Boolean

Specifies an HTTPS Client Certificate for use with server authentication. PKCS#12 certificates are not supported. This method accepts an associative array with the following parameters:

  • certificate_file: The filename of the Client Certificate file
  • key_file: The filename of the key file. You do not need to specify a key file if the key is embedded in the Client Certificate file (which might be the case when using PEM format).
  • type: Either "PEM" or "DER"
  • passphrase: The string passphrase to use if the key is encrypted
  • obfuscated_passphrase: The obfuscated string passphrase to use if the key is encrypted.

Note

If any of the parameters are set incorrectly, you'll likely get a -35 error when making a request.

SetCookie(cookie As String) As Boolean

Adds the specified cookie to the player storage and enables the cookie parsing/sending engine. The cookie can be either a single line in Netscape/Mozilla format or a standard HTTP-style header (i.e. Set-Cookie:). You can also carry out commands by passing these exact strings to the method:

  • "ALL": Erases all cookies held in memory.
  • "SESS": Erases all session cookies held in memory.
  • "RELOAD": Loads all cookies from files specified by SetCookieFile() calls.
SetCookieFile(filename As String) As Boolean

Adds cookies to the player storage using the specified cookie file and enables the cookie parsing/sending engine. The cookie data can be in either Netscape/Mozilla format or standard HTTP format.

GetCookies() As roList

Returns a string list of all cookies (including expired cookies).

EnableEncodings(enable As Boolean) As Boolean

Enables HTTP compression, which communicates to the server that the system can accept any encoding that the roUrlTransfer object is capable of decoding by itself. This currently includes "deflate" and "gzip", which allow for transparent compression of responses. Clients of the roUrlTransfer instance see only the decoded data and are unaware of the encoding being used.

Note

HTTP compression is enabled by default in firmware versions 6.0.x and later.

SetUserAndPassword(a As String, b As String) As Boolean
 
Head() As Object

Performs a synchronous HTTP HEAD request and returns the resulting response code and headers through an roURLEvent object. In the event of catastrophic failure (e.g. an asynchronous operation is already active), a null object is returned.

Escape(unescaped As String) As String

Converts the provided string to a URL-encoded string. All characters that could be misinterpreted in a URL context are converted to the %XX form.

Unescape(a As String) As String
 
GetUrl() As String
 
SetProxy(proxy As String) As Boolean

Sets the name or address of the proxy server that will be used by the roUrlTransfer instance. The proxy string should be formatted as follows: "http://user:password@hostname:port". It can contain up to four "*" characters; each "*" character can be used to replace one octet from the current IP address. For example, if the IP address is currently 192.168.1.2, and the proxy is set to "proxy-*-*", then the player will attempt to use a proxy named "proxy-192.168".

SetProxyBypass(hostnames As Array) As Boolean

Exempts the specified hosts from the proxy setting. The passed array should consist of one or more hostnames. The player will attempt to reach the specified hosts directly rather than using the proxy that has been specified with the SetProxy() method. For example, the hostname "example.com" would exempt "example.com", "example.com:80", and "www.example.com" from the proxy setting.

PutFromString(a As String) As Integer

Uses the HTTP PUT method to write the supplied string to the current URL and return the response code. Any response body is discarded; use roUrlTransfer.SyncMethod to retrieve the response body.

SetTimeout(milliseconds As Integer) As Boolean

Terminates the transfer if the request takes longer than the specified number milliseconds. Note that this includes the time taken by any name lookups, so setting this value too low will cause undesirable results. Passing 0 to the method disables the timeout. This method returns True upon success and False upon failure. In the event of failure, using the GetFailureReason() method may provide more information. If the operation times out, the status return is -28.

SetUserAgent(a As String) As Boolean
 
PutFromFile(a As String) As Integer

Uses the HTTP PUT method to write the contents of the specified file to the current URL and return the response code. Any response body is discarded; use roUrlTransfer.SyncMethod to retrieve the response body.

AsyncPutFromString(a As String) As Boolean

Uses the HTTP PUT method to write the supplied string to the current URL. Events of type roUrlEvent will be sent to the message port associated with the object. A False return indicates that the request could not be issued and no events will be delivered. Any response body is discarded; use roUrlTransfer.AsyncMethod to retrieve the response body.

AsyncPutFromFile(a As String) As Boolean

Uses the HTTP PUT method to write the contents of the specified file to the current URL. Events of type roUrlEvent will be sent to the message port associated with the object. A False return indicates that the request could not be issued and no events will be delivered. Any response body is discarded; use roUrlTransfer.AsyncMethod to retrieve the response body.

Delete() As Object

Uses the HTTP DELETE method to delete the resource at the current URL and return the response code. Any response body is discarded; use roUrlTransfer.SyncMethod to retrieve the response body.

AsyncDelete() As Boolean

Uses the HTTP DELETE method to delete the resource at the current URL. Events of type roUrlEvent will be sent to the message port associated with the object. A False return indicates that the request could not be issued and no events will be delivered. Any response body is discarded; use roUrlTransfer.AsyncMethod to retrieve the response body.

ClearHeaders() As Void

Removes all headers that would be supplied with an HTTP request.   

AddHeaders(a As Object) As Boolean

Adds one or more headers to HTTP requests. Pass headers to this object as an roAssociativeArray of name/value pairs. This method returns True upon success and False upon failure. All headers that are added with this method will continue to be sent with HTTP requests until ClearHeaders() is called.

SyncMethod(a As Object) As Object

Begins a synchronous HTTP request using the specified parameters (see the parameters described for AsyncMethod.) If the parameters are malformed then the method returns Invalid and calling GetFailureReason() may provide more information, otherwise the method returns a roUrlEvent instance containing the results of the request. It may take several minutes for a failing request to time out and BrightScript will be blocked waiting during that time, so use of this method is not recommended. The AsyncMethod method does not block and should be used instead.

SetRelativeLinkPrefix(prefix As String) As Boolean

Places the specified prefix in front of the URL if the URL is relative. Use this method to easily make file:/// URLs drive agnostic.

BindToInterface(interface As Integer) As Boolean

Ensures that the request only goes out over the specified network interface. By default, the request goes out over the most appropriate network interface (which may depend on the routing metric configured via roNetworkConfiguration). Note that if both interfaces are on the same layer 2 network, this method may not always work as expected due to the Linux weak host model. The default behavior can be selected by passing -1 to the method. This method returns False upon failure. In this case, the GetFailureReason() method may provide more information.

AsyncMethod(parameters As roAssociativeArray) As Boolean

Begins an asynchronous HTTP method request using the specified parameters (see below). If the request is started successfully, the method returns True and and will deliver an event. If the request could not be started, then the method returns False and will not deliver an event. If this occurs, you may be able to use the GetFailureReason() method to get more information.

The parameters are sepecifed using an roAssociativeArray instance that may contain the following members:

Name

Type

Description

method

String

An HTTP method. Normal values include "HEAD", "GET", "POST", "PUT", and "DELETE". Other values are supported; however, depending on server behavior, they may not work as expected.

request_body_string

String

A string containing the request body.

request_body_file

String

The name of a file that contains the request body

response_body_string

Boolean

If specified and set to True, the response will be stored in a string and provided via the roUrlEvent.GetString() method.

response_body_file

String

The name of the file that will contain the response body. The body is written to a temporary file and then renamed to the specified filename if successful.

response_body_resume_file

String

The name of the file that will contain the response body. For a GET request, a RANGE header is sent based on the current size of the file, which is written in place rather than using a temporary file.

response_body_object

String

Uses the response body to create an object of the specified type. See the entry for AsyncGetToObject() for supported object types.

response_pipe

roArray

Use a pipeline of handlers to process the response body as it is received. See below for more details.


The roArray response for response_pipe consists of one or more roAssociativeArray instances containing a filter description (see below). The last associative array is usually an output filter.

Name

Type

Description

hash

String

Calculate a hash (digest) of the data using the specified algorithm as it passes through the pipeline. Supported hashes include the following: "CRC32", "MD5", "SHA1", "SHA256", "SHA384", "SHA512". The resulting hash can be retrieved as a hexadecimal string using the roUrlEvent.GetHash() method.

decompress

String

Decompress the response body using the specified algorithm. Currently, the only supported algorithm is “gzip”. It is often easier to use an HTTP Content-Encoding rather than explicitly decompressing the body.

prefix_capture

Integer

Capture the specified number of bytes (between 1 and 16384) from the start of the stream and store them separately. The bytes can be retrieved using the roUrlEvent.GetPrefix() method, but they cannot be passed on to subsequent filters.

output file

String

Output the pipeline to the specified file. The output is written to a temporary file and then renamed to the specified filename if successful.

output_string

Boolean

If specified and set to True, the response will be stored in a string and provided via the roUrlEvent.GetString() method.


Examples

The following code example specifies an array of handlers to filter the response body of an HTTP request.

url = CreateObject("roUrlTransfer")
pipe = [ { decompress: "gzip"}, { hash: "MD5" }, { output_file: "test.txt" } ]
result = url.AsyncMethod({ method: "GET", response_pipe: pipe })

This example shows how to make an HTTP request with BrightScript:

sub makeHttpRequest(url as String) as String
    urlTransfer = CreateObject("roUrlTransfer")
    urlTransfer.SetUrl(url)
    
    if urlTransfer.AsyncGetToString()
        responseCode = urlTransfer.GetResponseCode()
        if responseCode = 200 ' HTTP OK
            responseString = urlTransfer.GetToString()
            return responseString
        else
            ' Handle error case
            return ""
        end if
    else
        ' Handle error case
        return ""
    end if
end sub