Class
URLConnection
REST
Description
Used to send and receive data using the HTTP 1.1+ protocol.
Properties
Name |
Type |
Read-Only |
Shared |
|---|---|---|---|
✓ |
|||
Methods
Name |
Parameters |
Returns |
Shared |
|---|---|---|---|
name As String |
|||
name As String |
|||
method As String, URL As String, file As FolderItem, timeout As Integer = 60 |
|||
method As String, URL As String, file As FolderItem, timeout As Integer = 0 |
|||
Events
Name |
Parameters |
Returns |
|---|---|---|
realm As String, ByRef name As String, ByRef password As String |
||
err As RuntimeException |
||
URL As String, HTTPStatus As Integer, file As FolderItem |
||
bytesReceived As Int64, totalBytes As Int64, newData As String |
||
Property descriptions
URLConnection.AllowCertificateValidation
AllowCertificateValidation As Boolean
URLConnection.FollowRedirects
FollowRedirects As Boolean
URLConnection.HTTPStatusCode
HTTPStatusCode As Integer
The HTTP status code when using the SendSync methods.
This property is read-only.
This code reads the HTTP status code after a synchronous request:
Var content As String content = MyConnection.SendSync("GET", "http://127.0.0.1:8080/GetData", 30) Var status As Integer = MyConnection.HTTPStatusCode
URLConnection.Password
Password As String
The password to be used to authentication.
Unlike other supported operating systems where user authentication is done via the AuthenticationRequested event, on Android, the UserName and Password must be provided (via properties) before sending the request.
Important
This property is only supported for Android.
URLConnection.UserName
UserName As String
The username to be used to authentication.
Unlike other supported operating systems where user authentication is done via the AuthenticationRequested event, on Android, the UserName and Password must be provided (via properties) before sending the request.
Important
This property is only supported for Android.
Method descriptions
URLConnection.ClearRequestHeaders
ClearRequestHeaders
Clears all of the request headers, which is useful if you are using the socket to send a different request.
mySocket.ClearRequestHeaders
URLConnection.Disconnect
Disconnect
Disconnects the socket.
A disconnected socket is not set to Nil and may be reused.
URLConnection.RequestHeader
RequestHeader(name As String) As String
Gets the request header with the key of name. The Name parameter's encoding is converted to ASCII. If the header does not exist in the request headers, an empty String is returned. Raises a RuntimeException if the encoding could not be converted to ASCII.
URLConnection.RequestHeader
RequestHeader(name As String, Assigns value As String)
Sets the request header with the key of name. The Name parameter's encoding is converted to ASCII.
The parameter
nameis the name of the key to get or set andvalueist the value for the key.Sets an API key as a token in the request header:
Self.RequestHeader("Authorization") = "MyAPIKey" mySocket.Send("GET", "http://www.webservice.com/GetData")
URLConnection.ResponseHeader
ResponseHeader(name As String) As String
Gets a response header.
URLConnection.ResponseHeaders
ResponseHeaders As Iterator
Used to iterate over all response headers.
Var connection As New URLConnection Var headers() As Pair For Each header As Pair In connection.ResponseHeaders headers.AddRow(header.Left : header.Right) Next
URLConnection.Send
Send(method As String, URL As String, file As FolderItem, timeout As Integer = 60)
Asynchronously sends a request using an HTTP method such as GET or POST. Send can be used to send both standard "http" and secure "https" requests. The timeout is in seconds.
If you pass "GET" as the method, the FileReceived event will be called with the file received from the server passed to it.
URLConnection.Send
Send(method As String, URL As String, timeout As Integer = 60)
Asynchronously sends a request using an HTTP method such as GET or POST. Send can be used to send both standard "http" and secure "https" requests. The timeout is in seconds.
If you pass "GET" as the method, or use the Send method to communicate with the server, the ContentReceived event will be called with the content received from the server passed to it.
Note
The timeout is in seconds and currently can be a maximum of 60 seconds (75 on macOS). A connection that times out will raise the Error event. You can view the timeout length on macOS with this Terminal command:
sysctl net.inet.tcp.keepinit. You can change it using this command (specify the value in milliseconds):sysctl net.inet.tcp.keepinit=30000.This example sends a request. The ContentReceived event is called with the response:
MyConnection.Send("GET", "http://127.0.0.1:8080/GetData")Sends a GET request, saving (downloading) the response to a file sent to the FileReceived event:
Var outputFile As FolderItem = SpecialFolder.Documents.Child("data.json") MyConnection.Send("GET", "http://127.0.0.1:8080/GetData", outputFile)To make a secure request, use "https" in the URL:
Var outputFile As FolderItem = SpecialFolder.Documents.Child("data.json") MyConnection.Send("GET", "https://www.mydomain.com/GetData", outputFile)
URLConnection.SendSync
SendSync(method As String, URL As String, file As FolderItem, timeout As Integer = 0)
Synchronously sends a request using an HTTP method such as GET or POST and returns the output in file. The results are saved to the supplied file. Send can be used to send both standard http and secure https requests. The timeout is in seconds.
URLConnection.SendSync
SendSync(method As String, URL As String, timeout As Integer = 0) As String
Synchronously sends a request using an HTTP method such as GET or POST. Results are returned as a String. Send can be used to send both standard http and secure https requests. The timeout is in seconds.
Note
Be aware that calling SendSync can cause your app's UI to "freeze" while it waits for the result. For normal processing you may want to use the asynchronous Send method instead, which calls the ContentReceived or FileReceived events when data is received.
This method raises a RuntimeException if an App Transport Security error occurs on macOS due to using a non-secure URL without the appropriate entry in the plist.
Var content As String content = MyConnection.SendSync("GET", "http://127.0.0.1:8080/GetData", 30)Sends a GET request, saving the response to a file:
Var outputFile As FolderItem = SpecialFolder.Documents.Child("data.json") MyConnection.SendSync("GET", "http://127.0.0.1:8080/GetData", outputFile, 30)To make a secure request, use "https" in the URL:
Var outputFile As FolderItem = SpecialFolder.Documents.Child("data.json") MyConnection.SendSync("GET", "https://www.mydomain.com/GetData", outputFile, 30)
URLConnection.SetRequestContent
SetRequestContent(content As String, mimeType As String)
Sets the content data and content type to be sent to the server.
Sends a POST request with JSON:
Var json As New JSONItem json.Value("ID") = 123456 mySocket.SetRequestContent(json.ToString, "application/json") mySocket.Send("POST", "http://127.0.0.1:8080/GetCustomer")To send form information, you build the String yourself:
' Build form String Var formText As String = "firstName=Bob&lastName=Roberts" ' POST it mySocket.SetRequestContent(formText, "application/x-www-form-urlencoded") mySocket.Send("POST", "http://www.webserviceurl.com")
Event descriptions
URLConnection.AuthenticationRequested
AuthenticationRequested(realm As String, ByRef name As String, ByRef password As String) As Boolean
Called when the connection requires HTTP basic authentication. Set the name and password and return True.
Important
This event is not supported for Android. The UserName and Password properties must be populated before the connection is made.
Specify a name and password:
name = "MyUserName" password = "MyPassword" Return True
URLConnection.ContentReceived
ContentReceived(URL As String, HTTPStatus As Integer, content As String)
Called when a new page has been retrieved from the server as a result of calling Send.
The encoding of content is set to the content-type encoding (charset) of the incoming content.
URLConnection.Error
Error(err As RuntimeException)
Called when an HTTP error occurs. When the error is a network-level failure (such as a connection timeout, SSL certificate error, or lost connection), err will be a NetworkException.
The
ErrorNumbervalues in the err exception vary by platform.macOS
Value
Constant
Description
-1
NSURLErrorUnknown
An unknown error occurred.
-999
NSURLErrorCancelled
The connection was cancelled.
-1000
NSURLErrorBadURL
A malformed URL prevented the connection from being initiated.
-1001
NSURLErrorTimedOut
The connection timed out.
-1002
NSURLErrorUnsupportedURL
The URL scheme is not supported.
-1003
NSURLErrorCannotFindHost
The host name could not be found.
-1004
NSURLErrorCannotConnectToHost
A connection could not be established to the host.
-1005
NSURLErrorNetworkConnectionLost
The network connection was lost.
-1006
NSURLErrorDNSLookupFailed
The DNS lookup for the host failed.
-1007
NSURLErrorHTTPTooManyRedirects
The request was redirected too many times.
-1008
NSURLErrorResourceUnavailable
The requested resource could not be retrieved.
-1009
NSURLErrorNotConnectedToInternet
The device is not connected to the internet.
-1010
NSURLErrorRedirectToNonExistentLocation
The connection was redirected to a non-existent location.
-1011
NSURLErrorBadServerResponse
The server returned an invalid response.
-1012
NSURLErrorUserCancelledAuthentication
The connection was cancelled by the user during authentication.
-1013
NSURLErrorUserAuthenticationRequired
Authentication is required to access the resource.
-1014
NSURLErrorZeroByteResource
The server reported the resource as having zero length.
-1015
NSURLErrorCannotDecodeRawData
The raw data could not be decoded.
-1016
NSURLErrorCannotDecodeContentData
The content data could not be decoded.
-1017
NSURLErrorCannotParseResponse
The response could not be parsed.
-1018
NSURLErrorInternationalRoamingOff
The connection failed because international roaming is disabled.
-1019
NSURLErrorCallIsActive
The connection failed because a call is active.
-1020
NSURLErrorDataNotAllowed
The cellular network disallowed the connection.
-1021
NSURLErrorRequestBodyStreamExhausted
The request body stream was exhausted.
-1022
NSURLErrorAppTransportSecurityRequiresSecureConnection
App Transport Security disallowed the connection because it does not use a secure connection.
-1100
NSURLErrorFileDoesNotExist
The file does not exist.
-1101
NSURLErrorFileIsDirectory
The requested resource is a directory.
-1102
NSURLErrorNoPermissionsToReadFile
The file could not be read due to insufficient permissions.
-1103
NSURLErrorDataLengthExceedsMaximum
The data length exceeds the maximum allowed.
-1201
NSURLErrorSecureConnectionFailed
An attempt to establish a secure connection failed.
-1202
NSURLErrorServerCertificateHasBadDate
The server certificate has an invalid date.
-1203
NSURLErrorServerCertificateUntrusted
The server certificate is not trusted.
-1204
NSURLErrorServerCertificateHasUnknownRoot
The server certificate is not signed by a known certificate authority.
-1205
NSURLErrorServerCertificateNotYetValid
The server certificate is not yet valid.
-1206
NSURLErrorClientCertificateRejected
The server rejected the client certificate.
-1207
NSURLErrorClientCertificateRequired
The server requires a client certificate.
-2000
NSURLErrorCannotLoadFromNetwork
The resource can only be loaded over the network but the network is unavailable.
-3000
NSURLErrorCannotCreateFile
A downloaded file could not be created.
-3001
NSURLErrorCannotOpenFile
A downloaded file could not be opened.
-3002
NSURLErrorCannotCloseFile
A downloaded file could not be closed.
-3003
NSURLErrorCannotWriteToFile
A downloaded file could not be written to.
-3004
NSURLErrorCannotRemoveFile
A downloaded file could not be removed.
-3005
NSURLErrorCannotMoveFile
A downloaded file could not be moved.
-3006
NSURLErrorDownloadDecodingFailedMidStream
Decoding of the downloaded data failed mid-stream.
-3007
NSURLErrorDownloadDecodingFailedToComplete
Decoding of the downloaded data failed to complete.
Windows
Value
Constant
Description
12001
ERROR_INTERNET_OUT_OF_HANDLES
No more handles could be generated.
12002
ERROR_INTERNET_TIMEOUT
The request timed out.
12003
ERROR_INTERNET_EXTENDED_ERROR
An extended error was returned from the server.
12004
ERROR_INTERNET_INTERNAL_ERROR
An internal error occurred.
12005
ERROR_INTERNET_INVALID_URL
The URL is invalid.
12006
ERROR_INTERNET_UNRECOGNIZED_SCHEME
The URL scheme could not be recognized or is not supported.
12007
ERROR_INTERNET_NAME_NOT_RESOLVED
The server name could not be resolved.
12008
ERROR_INTERNET_PROTOCOL_NOT_FOUND
The requested protocol could not be located.
12012
ERROR_INTERNET_SHUTDOWN
WinINet is being shut down or unloaded.
12017
ERROR_INTERNET_OPERATION_CANCELLED
The operation was cancelled because the handle was closed before the operation completed.
12029
ERROR_INTERNET_CANNOT_CONNECT
The attempt to connect to the server failed.
12030
ERROR_INTERNET_CONNECTION_ABORTED
The connection with the server was terminated.
12031
ERROR_INTERNET_CONNECTION_RESET
The connection with the server was reset.
12037
ERROR_INTERNET_SEC_CERT_DATE_INVALID
The SSL certificate has an invalid date. The certificate may be expired.
12038
ERROR_INTERNET_SEC_CERT_CN_INVALID
The SSL certificate common name (host name) does not match the server.
12044
ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED
The server requires client authentication.
12045
ERROR_INTERNET_INVALID_CA
The Certificate Authority that generated the server certificate is unknown.
12055
ERROR_INTERNET_SEC_CERT_ERRORS
The SSL certificate contains errors.
12056
ERROR_INTERNET_SEC_CERT_NO_REV
The SSL certificate has no revocation information.
12057
ERROR_INTERNET_SEC_CERT_REV_FAILED
Revocation of the SSL certificate failed.
12150
ERROR_HTTP_HEADER_NOT_FOUND
The requested header could not be located.
12151
ERROR_HTTP_DOWNLEVEL_SERVER
The server did not return any headers.
12152
ERROR_HTTP_INVALID_SERVER_RESPONSE
The server response could not be parsed.
12153
ERROR_HTTP_INVALID_HEADER
The supplied header is invalid.
12155
ERROR_HTTP_HEADER_ALREADY_EXISTS
The header could not be added because it already exists.
12156
ERROR_HTTP_REDIRECT_FAILED
The redirection failed because the scheme changed or all redirect attempts failed.
12157
ERROR_INTERNET_SECURITY_CHANNEL_ERROR
An internal error occurred while loading the SSL libraries.
12163
ERROR_INTERNET_DISCONNECTED
The internet connection has been lost.
12164
ERROR_INTERNET_SERVER_UNREACHABLE
The server is unreachable.
12165
ERROR_INTERNET_PROXY_SERVER_UNREACHABLE
The designated proxy server cannot be reached.
12169
ERROR_INTERNET_SEC_INVALID_CERT
The SSL certificate is invalid.
12170
ERROR_INTERNET_SEC_CERT_REVOKED
The SSL certificate was revoked.
Linux
Value
Constant
Description
0
SOUP_STATUS_NONE
No status available. The request has not completed or failed before a response was received.
400
SOUP_STATUS_BAD_REQUEST
Bad Request.
401
SOUP_STATUS_UNAUTHORIZED
Unauthorized.
403
SOUP_STATUS_FORBIDDEN
Forbidden.
404
SOUP_STATUS_NOT_FOUND
Not Found.
405
SOUP_STATUS_METHOD_NOT_ALLOWED
Method Not Allowed.
407
SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED
Proxy Authentication Required.
408
SOUP_STATUS_REQUEST_TIMEOUT
Request Timeout.
409
SOUP_STATUS_CONFLICT
Conflict.
410
SOUP_STATUS_GONE
Gone.
500
SOUP_STATUS_INTERNAL_SERVER_ERROR
Internal Server Error.
501
SOUP_STATUS_NOT_IMPLEMENTED
Not Implemented.
502
SOUP_STATUS_BAD_GATEWAY
Bad Gateway.
503
SOUP_STATUS_SERVICE_UNAVAILABLE
Service Unavailable.
504
SOUP_STATUS_GATEWAY_TIMEOUT
Gateway Timeout.
505
SOUP_STATUS_HTTP_VERSION_NOT_SUPPORTED
HTTP Version Not Supported.
Display information about the error:
ErrorLabel.Text = e.Reason
URLConnection.FileReceived
FileReceived(URL As String, HTTPStatus As Integer, file As FolderItem)
n a download of a file is completed as a result of calling Send and passing a FolderItem.
URLConnection.HeadersReceived
HeadersReceived(URL As String, HTTPStatus As Integer)
Called when headers are received from the server.
URLConnection.ReceivingProgressed
ReceivingProgressed(bytesReceived As Int64, totalBytes As Int64, newData As String)
Call periodically as data is received.
URLConnection.SendingProgressed
SendingProgressed(bytesSent As Int64, bytesLeft As Int64)
Called periodically as data is sent/uploaded.
Notes
Usage on Linux requires libsoup3 with a fallback to libsoup2-4.
URLConnection handles both standard "http" connections and secure "https" connections.
Standard Method Definitions
GET and POST are most commonly used, but there are other methods as well. For example, to get just the headers you can use the HEAD method. The full list of methods is available on the W3 HTTP/1.1 Method Definition page.
macOS information (app transport security)
Starting with OS X 10.11, you have to use secure "https" connections or you will get this error: "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection". To continue to connect to non-secure "http" connections that you do not control you'll have to provide a plist with a temporary exception specified for each site you are accessing via http:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>firstsite.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>secondsite.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
</dict>
</plist>
If you don't know the specific sites, you can request access to everything using a single key:
<key>NSAppTransportSecurity</key>
<dict>
<!-- Include to allow all connections; avoid if possible -->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Apple may reject an App Store submission if the app uses these settings without valid reasons.
For more information about this, refer to NSAppTransportSecurity in Apple's docs.
For more information: Using Non-Secure URLs on macOS and iOS, Using a plist
To test a site to see what plist exceptions it might need you can use this Terminal command:
/usr/bin/nscurl --ats-diagnostics --verbose https://example.com
Compatibility
Project Types |
All |
Operating Systems |
All |
See also
Object parent class; Using Non-Secure URLs on macOS and iOS, Using a plist topics; Paw Extension on GitHub