Class

Xojo.Net.HTTPSocket


Warning

This item was deprecated in version 2020r2. Please use URLConnection as a replacement.

Description

Used to send and receive data via the HTTP 1.1 protocol.

Properties

Name

Type

Read-Only

Shared

ValidateCertificates

Boolean

Methods

Name

Parameters

Returns

Shared

ClearRequestHeaders

Disconnect

ResponseHeader

name As String

String

SetRequestContent

data As MemoryBlock, mimeType As String

Events

Name

Parameters

Returns

AuthenticationRequired

realm As String, ByRef name As String, ByRef password As String

Error

err As RuntimeException

FileReceived

URL As String, HTTPStatus As Integer, file As FolderItem

HeadersReceived

URL As String, HTTPStatus As Integer

PageReceived

URL As String, HTTPStatus As Integer, content As MemoryBlock

ReceiveProgress

bytesReceived As Int64, totalBytes As Int64, newData As MemoryBlock

SendProgress

bytesSent As Int64, bytesLeft As Int64

Property descriptions


Xojo.Net.HTTPSocket.ValidateCertificates

ValidateCertificates As Boolean

When set to True, the socket verifies the supplied certificate for authenticity. The Error event is called if the validation fails. The default value is True.

Method descriptions


Xojo.Net.HTTPSocket.ClearRequestHeaders

ClearRequestHeaders

Clears all of the request headers, which is useful if you are using the socket to send a different request.

mySocket.ClearRequestHeaders

Xojo.Net.HTTPSocket.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.


Xojo.Net.HTTPSocket.ResponseHeader

ResponseHeader(name As String) As String

Gets a response header.


Xojo.Net.HTTPSocket.SetRequestContent

SetRequestContent(data As MemoryBlock, mimeType As String)

Sets the content data and content type to be sent to the server.

Sends a POST request, converting JSON data to a MemoryBlock before sending:

Using Xojo.Core
Using Xojo.Data

' Simple data in a Dictionary
Var info As New Dictionary
info.Value("ID") = 123456

' Convert to JSON text
Var json As Text
json = GenerateJSON(info)

' Convert to MemoryBlock
Var data As MemoryBlock
data = TextEncoding.UTF8.ConvertTextToData(json)

mySocket.SetRequestContent(data, "application/json")
mySocket.Send("POST", "http://127.0.0.1:8080/GetCustomer")

To send form information, you build the text yourself:

Using Xojo.Core
Using Xojo.Data

' Build form text
Var formText As Text = "firstName=Bob&lastName=Roberts"

' Convert to MemoryBlock
Var postData As Xojo.Core.MemoryBlock
postData = Xojo.Core.TextEncoding.UTF8.ConvertTextToData(formText)

' POST it
MyHttpSocket.SetRequestContent(postData, "application/x-www-form-urlencoded")
MyHttpSocket.Send("POST", "http://www.webserviceurl.com")

Event descriptions


Xojo.Net.HTTPSocket.AuthenticationRequired

AuthenticationRequired(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

Xojo.Net.HTTPSocket.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: * Windows HTTP Errors * macOS NSURLError.h * Linux libsoup status codes

Display information about the error:

ErrorLabel.Value = err.Reason

Xojo.Net.HTTPSocket.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.


Xojo.Net.HTTPSocket.HeadersReceived

HeadersReceived(URL As String, HTTPStatus As Integer)

Called when headers are received from the server.


Xojo.Net.HTTPSocket.PageReceived

PageReceived(URL As String, HTTPStatus As Integer, content As MemoryBlock)

Called when a new page has been retrieved from the server as a result of calling Send.

Convert incoming JSON content from a MemoryBlock into a Dictionary:

Var jsonData As Text
' Convert the content returned from an API from a MemoryBlock to Text.
jsonData = Xojo.Core.TextEncoding.UTF8.ConvertDataToText(content)

' Parse the JSON result into a Dictionary
Var jsonDict As Xojo.Core.Dictionary
jsonDict = Xojo.Data.ParseJSON(jsonData)

Xojo.Net.HTTPSocket.ReceiveProgress

ReceiveProgress(bytesReceived As Int64, totalBytes As Int64, newData As MemoryBlock)

Call periodically as data is received.


Xojo.Net.HTTPSocket.SendProgress

SendProgress(bytesSent As Int64, bytesLeft As Int64)

Called periodically as data is sent/uploaded.

Notes

Usage on Linux requires libsoup 2.4.

In order to use HTTPSocket with TLSv1.2 on Windows 7, KB3140245 needs to be installed using Windows Update and the DefaultSecureProtocols Registry subkey needs to be configured.

TLSv1.2 is not supported when using Xojo.Net.HTTPSocket on OS X 10.7 and 10.8 due to limitations of those systems.

Use an HTTPSocket when you need to upload or download information on the web. You can download files, communicate with REST web services and other APIs and do any type of HTTP 1.1 communication.

HTTPSocket handles both standard "http" connections and secure "https" connections.

HTTPSocket has a default timeout of 60 seconds, which cannot be changed.

Unlike the classic URLConnection, Xojo.Net.HTTPSocket does not support synchronous usage. It only works asynchronously by using the events as described below.

Do not attempt to re-use a socket that is still in use (e.g. directly from the PageReceived or FileReceived events). One solution is to use a separate Timer that checks if the socket is available before attempting to use it again, but for bests results you will probably want to create a new socket.


Constants

SizeUnknown -1 An unknown number of bytes was received.


Ios and os x information (app transport security)

Starting with iOS 9 and OS X 10.11 (with 2018r4), 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 your App Store submission if you app uses these settings without valid reasons.

For more information about this, refer to NSAppTransportSecurity in Apple's docs.

Apparently there is a bug in iOS that prevents the use of IP addresses in this plist. So to enable http on your local computer for testing use "localhost" rather than "127.0.0.1" and be sure to use "http://localhost" in your URLs instead of "http://127.0.0.1".

For more information: Using Non-Secure URLs on macOS and iOS

Compatibility

All project types on all supported operating systems.

See also

Object parent class; URLConnection, MemoryBlock, TextEncoding classes; Using a plist topic