Class
HTTPSecureSocket
Warning
This item was deprecated in version 2019r1. Please use URLConnection as a replacement.
Description
Used to do secure transmissions via the HTTP 1.0 protocol using the SSL or TLS protocols.
Properties
Name |
Type |
Read-Only |
Shared |
---|---|---|---|
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
Form As Dictionary |
|||
URL As String, [File As FolderItem] |
|||
[Encoding As TextEncoding] |
|||
URL As String, [File As FolderItem] |
|||
Count As Integer, [Enc As TextEncoding] |
|||
[Encoding As TextEncoding] |
|||
Method As String, URL As String, [File As FolderItem] |
|||
Form As Dictionary |
|||
Data As String |
Events
Name |
Parameters |
Returns |
---|---|---|
Realm As String, Headers As InternetHeaders, ByRef Name As String, ByRef Password As String |
||
URL As String, HTTPStatus As Integer, Headers As InternetHeaders, File As FolderItem |
||
Headers As InternetHeaders, HTTPStatus As Integer |
||
URL As String, HTTPStatus As Integer, Headers As InternetHeaders, Content As String |
||
Realm As String, Headers As InternetHeaders, ByRef Name As String, ByRef Password As String |
||
BytesReceived As Integer, TotalBytes As Integer, NewData As String |
||
Property descriptions
HTTPSecureSocket.Address
Address As String
The TCP/IP address to try to connect to.
In this example, the address has been entered into a TextField.
TCPSocket1.Address = TextField1.Text
HTTPSecureSocket.BytesAvailable
BytesAvailable As Integer
The number of bytes of data are available in the internal receive buffer.
This property is read-only.
TextField1.Text = Me.BytesAvailable.ToString
HTTPSecureSocket.BytesLeftToSend
BytesLeftToSend As Integer
The number of bytes left in the queue remaining to be sent.
This property is read-only.
This enables you to create a synchronous socket without needing to subclass it.
TextField1.Text = Me.BytesLeftToSend.ToString
HTTPSecureSocket.CertificateFile
CertificateFile As FolderItem
The file that contains the SSL certificate.
This example opens the certificate file and assigns it to the property.
Var f As FolderItem
f = FolderItem.ShowOpenFileDialog("text/plain")
If f <> Nil Then
Socket1.CertificateFile = f
End If
HTTPSecureSocket.CertificatePassword
CertificatePassword As String
The certificate password for the secure connection.
This example sets the certificate password from a TextField.
socket1.CertificatePassword=TextField1.Text
HTTPSecureSocket.CertificateRejectionFile
CertificateRejectionFile As FolderItem
The certificate rejection file.
This example gets the certificate rejection file from disk.
Var f As FolderItem
f = FolderItem.ShowOpenFileDialog("text/plain")
If f <> Nil Then
Socket1.CertificateRejectionFile = f
End If
HTTPSecureSocket.DefaultPort
DefaultPort As Integer
The default port used by the socket. The default value is 443.
HTTPSecureSocket.ErrorCode
ErrorCode As
A special case of LastErrorCode.
Returns the same as LastErrorCode except for these two conditions:
# If Get/Post/GetHeaders/SendRequest times out, then ErrorCode = -1 # When calling Get (the overloaded method that accepts a FolderItem as a parameter), if the file is a directory or could not be created then ErrorCode = 1
HTTPSecureSocket.Handle
Handle As Integer
This is the socket's internal descriptor and it can be used with Declare statements.
This property is read-only.
On Windows, Handle is a Socket, suitable for use in Declares on Windows.
On macOS and Linux, Handle is a UNIX socket descriptor.
The descriptor is platform-specific. If Handle is less than zero, the descriptor is not available.
HTTPSecureSocket.HTTPProxyAddress
HTTPProxyAddress As String
The proxy address; required only if you are connecting via proxy.
This example specifies the proxy address. The proxy serves as a “middleman" to provide additional security or anonymity.
Me.HTTPProxyAddress = "130.25.0.1"
HTTPSecureSocket.HTTPProxyPort
HTTPProxyPort As Integer
The proxy port; required only if you are connecting via proxy.
Socket1.HTTPProxyPort = 7443
HTTPSecureSocket.HTTPStatusCode
HTTPStatusCode As Integer
Returns the resulting code from the server.
This function can provide the status code when the socket is used in synchronous mode.
This example displays the status code in a TextField.
TextField1.Text = Str(Socket1.HTTPStatusCode)
HTTPSecureSocket.IsConnected
IsConnected As Boolean
Indicates whether the socket is currently connected.
This property is read-only.
For TCPSockets, a connection means you can send and receive data and are connected to a remote machine. For UDPSockets, this means that you are bound to the port and are able to send, receive, join or leave multicast groups, or set socket options.
If EasyUDPSocket1.IsConnected Then
' proceed using the connection
Else
MessageBox("Connection failed!")
End If
HTTPSecureSocket.LocalAddress
LocalAddress As String
The local IP address of the computer.
This property is read-only.
Var localIP As String = Socket1.LocalAddress
HTTPSecureSocket.NetworkInterface
NetworkInterface As NetworkInterface
Specifies which network interface the socket should use when binding.
You can get the network interface(s) of the user's computer by calling the GetNetworkInterface method of the System module.
Leaving this property set to Nil will use the currently selected interface. In the case of UDPSockets, if you assign a non-Nil value, the socket may not be able to receive broadcast messages. The behavior is OS-dependent; it appears to work on Windows but not on other supported operating systems. If you wish to send broadcast packets out, then you should not bind to a specific interface because the behavior is undefined.
This example specifies that the TCPSocket will use the first Network Interface on the user's computer.
TCPSocket1.NetworkInterface = System.NetworkInterface(0)
HTTPSecureSocket.Port
Port As Integer
The port to bind on or connect to.
On most operating systems, attempting to bind to a port less than 1024 causes a Error event to fire with an error number 107 unless the application is running with administrative permissions. This is due to security features built into the underlying OS.
You need to set the port property explicitly before any call to Listen or Connect as the Port property will be modified to reflect what the actual bound port is during the various stages of operation.
For instance, if you listen on port 8080 and a connection comes in, you can check the Port property to ensure that you're still listening on port 8080 (that the port hasn't been hijacked). Or, if you connect to a socket on port 8080, once the connection occurs, you can check to see what port the OS has bound you to. This will be a random-seeming port number.
This trick can be very useful when you do things like Listen on port 0. In that case, the OS will pick a port for you and listen on it. Then you can check the Port property to see which port the OS picked. This functionality is used for various protocols, such as FTP.
This example sets the Port to 8080.
TCPSocket1.Port = 8080
HTTPSecureSocket.RemoteAddress
RemoteAddress As String
The address of the remote machine you are connected to.
This property is read-only.
Use this instead of the Address property to determine the address of the machine you are actually connected to.
This example reports the address of the remote machine that the user is connected to. It is in the Connected event.
TextField1.Text = Me.RemoteAddress
HTTPSecureSocket.RequestHeaders
RequestHeaders As InternetHeaders
Request headers are sent to the server along with the action (GET, POST, etc.). They can contain data that the server might use to process your request. Some examples of common request headers are for things such as referring pages, the client name, OS CPU, and so forth.
Socket1.RequestHeaders.AppendHeader("Content-Type", "text/xml")
HTTPSecureSocket.SSLConnected
SSLConnected As Boolean
True if you have an SSL connection.
This property is read-only.
If Me.SSLConnected Then
' connection established with secure communications, proceed ...
Else
Exit
End If
HTTPSecureSocket.SSLConnecting
SSLConnecting As Boolean
True if the socket is in the process of doing a handshake to establish an SSL connection.
This property is read-only.
If Me.SSLConnecting Then
' proceed with connection
End If
HTTPSecureSocket.SSLConnectionType
SSLConnectionType As Integer
Specifies the type of SSL connection.
Note
Use the SSLSocket constant names for ConnectionType, and not the integer values so that the IDE can warn you when constants are removed or deprecated.
Set this property by assigning a SSLConnectionTypes value to it.
The default is TLSv1. If you need to change the connection type, close the connection first.
This example changes the connection type to TLSv1.
Socket1.SSLConnectionType = SSLSocket.SSLConnectionTypes.TLSv1
HTTPSecureSocket.SSLEnabled
SSLEnabled As Boolean
Set to True to specify an SSL connection.
If SSLEnabled is False, the SSLSocket transmits data just like a TCPSocket. This property can be toggled at any time.
Me.SSLEnabled = True
HTTPSecureSocket.Yield
Yield As Boolean
When you are using synchronous HTTP, your application may need to wait a noticeable amount of time to get or post a page. Setting Yield to True allows for events and other code to execute while waiting for a page. Yield is relevant when you pass the optional Timeout parameter with Get or GetHeaders. Set Yield to True just prior to a call to any of these methods.
Socket1.Yield = True
Method descriptions
HTTPSecureSocket.ClearRequestHeaders
ClearRequestHeaders
Clears all of the set request headers.
See the description of the SetRequestHeaders method for information on headers.
Socket1.ClearRequestHeaders
HTTPSecureSocket.Close
Close
Closes the socket's connection, closes any connections the socket may have, and resets the socket.
The only information that is retained after calling Close is the socket's port, address (in the case of TCPSockets), LastErrorCode properties, and data left in the socket's receive buffer. All other information is discarded.
This example closes the EasyTCPSockets that were open. The sockets were added to the main window.
Connector.Close
Listener.Close
HTTPSecureSocket.Connect
Connect
Attempts to connect.
For TCPSockets, the address and port properties must be set. For UDPSockets, the port property must be set. The Connect method binds a socket to a port. After calling Connect, the Port property will report the actual port you are bound to.
HTTPSecureSocket.Disconnect
Disconnect
Disconnects the socket, resets it, and fires a SocketCore Error event with a 102 error to let you know that the socket has been disconnected.
This example disconnects the EasyTCPSockets that were opened.
Connector.Disconnect
Listener.Disconnect
HTTPSecureSocket.EncodeFormData
EncodeFormData(Form As Dictionary) As String
Takes the key/value pairs from the specified Dictionary and formats them into a URL-encoded String.
The result can then be used in the URL to send data to a form with a GET action or as content for a POST.
HTTPSecureSocket.EndOfFile
EndOfFile As Boolean
Returns True when there's no more data left to read.
This code reads the rows and columns of data from a tab-delimited text file into a ListBox:
Var f As FolderItem
Var textInput As TextInputStream
Var rowFromFile, oneCell As String
f = FolderItem.ShowOpenFileDialog("text/plain") ' defined as a FileType
If f <> Nil Then
textInput = TextInputStream.Open(f)
textInput.Encoding = Encodings.UTF8
Do
rowFromFile = textInput.ReadLine
Var values() As String = rowFromFile.Split(Chr(9))
ListBox1.ColumnCount = values.Count
ListBox1.AddRow("")
Var col As Integer
For Each value As String In values
ListBox1.CellTextAt(ListBox1.LastAddedRowIndex, col) = value
col = col + 1
End For
Loop Until textInput.EndOfFile
textInput.Close
End If
This example reads each pair of bytes from a file and writes them in reverse order to a new file. The user chooses the source file using the Open-file dialog box and saves the new file using the Save as dialog box. The EOF property is used to terminate the Do...Loop.
Var readFile As FolderItem = FolderItem.ShowOpenFileDialog("text")
If readFile <> Nil Then
Var ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
ReadStream.LittleEndian = True
Var writeFile As FolderItem = FolderItem.ShowSaveFileDialog("", "")
If writeFile <> Nil Then
Var writeStream As BinaryStream = BinaryStream.Create(writeFile, True)
writeStream.LittleEndian = True
Do Until ReadStream.EndOfFile
writeStream.WriteInt8(ReadStream.ReadInt8)
Loop
writeStream = Nil
End If
readStream = Nil
End If
HTTPSecureSocket.Flush
Flush
Immediately sends the contents of internal write buffers to disk or to the output stream.
This function can be useful in point-to-point communication over sockets and similar connections: To optimize for transmission performance, some types of output streams try to collect small pieces of written data into one larger piece for sending instead of sending each piece out individually. By calling Flush, the data collection is stopped and the data is sent without further delay, reducing latency.
When using this on a stream that ends up as a file on disk, it is useful, too: Any short parts of previously written data are written to disk right away, ensuring the data is actually on disk if the application terminates abruptly, e.g. due to a crash.
Avoid calling this method too often. For example, do not call it between successive Write calls because you'll slow down performance without getting much benefit.
A typical use case would look like this:
mySocket.Write("you typed: ")
mySocket.Write(key)
mySocket.Write(".")
mySocket.Flush
HTTPSecureSocket.Get
Get(URL As String, [File As FolderItem])
Synchronously downloads the content from the URL directly to the FolderItem. When the download has finished, True is returned if successful, False if there was an error. TimeOut is the number of seconds to wait for the result.
For the synchronous version of these methods, set the Yield property to True to allow for background activities while waiting.
HTTPSecureSocket.Listen
Listen
Attempts to listen for incoming connections on the currently specified port.
After calling Listen, the Port property will report the actual port you are bound to.
HTTPSecureSocket.Lookahead
Lookahead([Encoding As TextEncoding]) As String
Returns a String, containing the data that is available in the internal queue without removing it.
The optional Encoding parameter enables you to specify the text encoding of the data to be returned. The default is Nil. Use the Encodings module to specify an encoding.
This example adds the contents of the internal queue to a TextArea. The Listener EasyTCPSocket has been added to the window.
TextArea1.AddText(listener.Lookahead)
HTTPSecureSocket.PageHeaders
PageHeaders As InternetHeaders
Provides access to the headers received from the server. This can be used to access the headers in synchronous mode.
HTTPSecureSocket.Poll
Poll
Polls the socket manually, which allows a socket to be used synchronously.
The EasyTCPSocket "Listener" has been added to the window.
Listener.Poll
HTTPSecureSocket.Post
Post(URL As String, [File As FolderItem])
Synchronously issues a POST command to the URL and downloads the result directly to the FolderItem. When the download has finished, True is returned if successful, False if there was an error. TimeOut is the number of seconds to wait for the result.
For the synchronous versions of this method, set the HTTPSecureSocket property to True to allow for background activities while waiting.
HTTPSecureSocket.Purge
Purge
Removes all data from the socket's internal receive buffer. It does not affect the socket's internal send buffer.
Listener.Purge
HTTPSecureSocket.Read
Read(Count As Integer, [Enc As TextEncoding]) As String
Reads Count bytes from the input stream and returns a String.
If provided, the optional parameter Enc specifies the text encoding to be defined for the String to be read.
If Count is higher than the amount of bytes currently available in the stream, all available bytes will be returned. Therefore, make sure to always consider the case that you get less than you requested. To see if you received all requested bytes, check the returned string's String property (avoid using Length as it may give a different number if the encoding is not nil).
If not enough memory is available, you get back an empty string.
This example reads the first 1000 bytes from a BinaryStream.
Var readFile As FolderItem = FolderItem.ShowOpenFileDialog("text/plain")
If readFile <> Nil Then
Var ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
ReadStream.LittleEndian = True
TextArea1.Text = ReadStream.Read(1000, Encodings.UTF8)
End If
HTTPSecureSocket.ReadAll
ReadAll([Encoding As TextEncoding]) As String
Reads all the data from the internal buffer.
This example reads all the data in the buffer into a TextArea.
TextField1.AddText(listener.ReadAll)
HTTPSecureSocket.SendRequest
SendRequest(Method As String, URL As String, [File As FolderItem])
Allows the user to synchronously send a request using an HTTP method other than GET or POST. Supply the method as a String, URL as a String and a FolderItem. Return a Boolean to indicate if it was successful. Data is saved to the FolderItem.
Common others methods are OPTIONS, HEAD, PUT, DELETE, TRACE and CONNECT as per RFC 2616 describing the HTTP 1.1 protocol.
HTTPSecureSocket.SetFormData
SetFormData(Form As Dictionary)
Takes the key/value pairs from the Dictionary and converts it to a URL-encoded String.
This method also sets the action to POST. After using this method, the form can be sent to the server with the POST action.
HTTPSecureSocket.SetPostContent
SetPostContent(Content As String, ContentType As String)
Sets the content data and content type to be sent to the server for a POST command.
HTTPSecureSocket.SetRequestContent
SetRequestContent(Content As String, ContentType As String)
Sets the content data and content type to be sent to the server for any command except HEAD.
If you will be reusing a socket without using the New operator, you must clear this value for requests that do not have content associated with them. For instance, If you do a POST with content followed by a GET that should not have content, you should set the content to an empty string.
HTTPSecureSocket.SetRequestHeader
SetRequestHeader(Name As String, Value As String)
Sets the value of a request header.
Request headers are sent to the server along with the action (GET, POST, etc.). They can contain data that the server might use to process your request. Some examples of common request headers are for things such as referring pages, the client name, OS CPU, and so forth.
This example sets a request header.
Socket1.SetRequestHeader("Content-Type", "text/xml")
HTTPSecureSocket.Write
Write(Data As String)
Writes the passed data to the output stream.
Note that in order to make sure that the data actually ends up on disk or gets sent to the socket it is connected to, the stream must either get closed or the Flush method be called. Otherwise, the data, if small, may end up temporarily in a write buffer before either a certain time has passed or more data is written. This buffering increases performance when writing lots of small pieces of data, but may be causing unwanted delays when another process, e.g. the other end of a socket connection, is waiting for the data. Consider calling the Flush method to reduce latencies that this buffering may cause in such cases.
If Write fails, an IOException will be raised.
This example displays the Save As dialog box and writes the contents of the TextArea1 to a text file.
Var f As FolderItem
Var stream As BinaryStream
f = FolderItem.ShowSaveFileDialog(FileTypes1.Text, "Untitled.txt")
If f<> Nil Then
stream = BinaryStream.Create(f, True)
stream.Write(TextArea1.Text)
stream.Close
End If
Event descriptions
HTTPSecureSocket.AuthenticationRequired
AuthenticationRequired(Realm As String, Headers As InternetHeaders, ByRef Name As String, ByRef Password As String) As Boolean
Executes when a site that requires authentication connects. AuthenticationRequired supports Digest authentication.
If your connection requires a userid/password, set them in this event and return True:
Name = "UserID"
Password = "P4$$w0rd"
Return True
HTTPSecureSocket.Connected
Connected
Executes when the connection is established with the server.
HTTPSecureSocket.DownloadComplete
DownloadComplete(URL As String, HTTPStatus As Integer, Headers As InternetHeaders, File As FolderItem)
Executes when a download is complete after using the Get method.
URL contains the URL that was downloaded. File is the FolderItem the data was downloaded to, and Headers is a dictionary of the HTTP headers that were returned by the server. The HTTPStatus code is also passed to this event. These codes are used for messages such as "Page not found" (error 404), and so forth.
HTTPSecureSocket.HeadersReceived
HeadersReceived(Headers As InternetHeaders, HTTPStatus As Integer)
Executes when the headers have been retrieved from the server.
HTTPSecureSocket.PageReceived
PageReceived(URL As String, HTTPStatus As Integer, Headers As InternetHeaders, Content As String)
Executes when a new page has been retrieved from the server. It provides the URL that was requested and the HTTP headers from the web server.
The HTTPStatus code is also passed to this event. These codes are used for messages such as "Page not found" (error 404), and so forth.
HTTPSecureSocket.ProxyAuthenticationRequired
ProxyAuthenticationRequired(Realm As String, Headers As InternetHeaders, ByRef Name As String, ByRef Password As String) As Boolean
Executes when a site that requires via proxy authentication connects. ProxyAuthenticationRequired also supports Digest authentication.
HTTPSecureSocket.ReceiveProgress
ReceiveProgress(BytesReceived As Integer, TotalBytes As Integer, NewData As String)
The parameters provide the current number of bytes received and the total number of bytes (if available). ReceiveProgress executes periodically during the download process.
HTTPSecureSocket.SendProgress
SendProgress(BytesSent As Integer, BytesLeft As Integer)
Occurs when your network provider queues your data in chunks and is about to send the next chunk.
The parameters indicate the amount of progress that has been made during the send. Returns a Boolean.
Returning True from this event causes the send to be cancelled. This does not close the socket's connection; it only clears the buffer. After all of the data has been transferred you will get a final SendProgress event followed by a SendComplete event.
bytesSent is the number of bytes that were sent in the chunk, not the total number of bytes sent.
Notes
Note
If you need HTTP 1.1 support, use URLConnection instead.
Use the HTTPSecureSocket class to perform secure communications via the HTTP protocol. It is identical to the URLConnection class except that it is derived from the SSLSocket class instead of the TCPSocket class. This means that you can use the Secure property of SSLSocket to switch to HTTPS. When you set Secure to True, the default port changes from 80 to 443. It supports HTTP proxies while in secure mode.
If you use a constructor in a subclass of HTTPSecureSocket, you must call the Super class's constructor in your subclass's constructor. The subclass will not work unless this is done. You can use the Super keyword for this purpose.
App transport security
Starting with OS X 10.11 and 2018r4, your apps 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". You can work around this by providing a plist with your app to indicate what non-secure URLs you are using. For more information: * Using Non-Secure URLs on macOS and iOS
Xojo cloud
Web apps running on Xojo Cloud first have to use the FirewallPort class to open the port used to connect to an outside web server.
Sample code
A simple, secure connection:
Dim secureSite As New HTTPSecureSocket
secureSite.Secure = True
secureSite.ConnectionType = SSLSocket.TLSv12
Dim data As String
data = secureSite.Get("https://www.example.com", 30)
The following example posts a simple form:
Dim form As Dictionary
Dim socket1 As HTTPSecureSocket
socket1 = New HTTPSecureSocket
socket1.Secure = True
' create and populate the form object
form = New Dictionary
form.Value("firstname") = "Bob"
form.Value("lastname") = "Brown"
' setup the socket to POST the form
socket1.SetFormData(form)
socket1.Post("https://www.myformlocation.com/form.php")
Compatibility
All project types on all supported operating systems.
See also
SSLSocket parent class; URLConnection, URLConnection, SSLSocket, SocketCore, TCPSocket, URLConnection classes.