Class
URLConnection
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 |
|||
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
When set to True, the connection requires that the server's certificate is valid. The Error event is called if the certificate is not valid. The default value is True.
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
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, but is no longer in a useful state. You should create a new socket rather than attempting to re-use a disconnected socket.
URLConnection.RequestHeader
RequestHeader(name As String) As String
Sets the request header with the key of name. The Name parameter's encoding is 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.
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.
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, the ContentReceived event will be called with the content received from the server passed to it.
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)
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) 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.
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)
Called when the connection requires HTTP basic authentication. Set the name and password and return True.
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.
The ErrorNumber values in the err exception vary by platform. Here are links to errors by platform:
Display information about the error:
ErrorLabel.Text = e.Reason
URLConnection.FileReceived
FileReceived(URL As String, HTTPStatus As Integer, file As FolderItem)
Called when 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 libsoup 2.4.
URLConnection handles both standard "http" connections and secure "https" connections.
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
All project types on all supported operating systems.
See also
Object parent class; Using Non-Secure URLs on macOS and iOS, Using a plist topics; Paw Extension on GitHub