HTTP (Web) Communication
From Xojo Documentation
|You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!|
HTTP (HyperText Transfer Protocol) is the protocol that web browsers use. To communicate using the HTTP protocol use the URLConnection class. This class contains methods and properties that enable you to do all types of HTTP communication such as retrieving a URL or posting a form.
Some of the more common things you do with a URLSocket is to get the contents of a web service and post forms to web pages. To use a URLSocket, you can drag it from the Library onto your Layout. Or you can add a subclass to your project.
There are two ways to send HTTP requests to URLs: Send and SendSync. The Send method is asynchronous so the URL request will not force you app to wait until it returns. The SendSync method is synchronous so your app will wait until the data from the request is received (or it times out). You can make a SendSync call in a Thread to prevent your app from waiting.
When you send a request you have to tell it the sending method. GET and POST are the two most common, but there are others.
This code sends a GET request to a web service and waits up to 30 seconds for a response:
The data will be in the content variable when the response is received.
To do this same call asynchronously, you call it like this:
With this method, the URLConnection.ContentReceived event is called when the data is received. You will need to implement the event handler so that you can get the data.
Downloading a File
Both Send and SendSync have optional parameters to request a file. To synchronously request a file you also provide a FolderItem for it to be saved to:
MyConnection.SendSync("GET", "https://127.0.0.1:8080/GetData%22, outputFile, 30)
And the asynchronous call is similar:
MyConnection.Send("GET", "http://127.0.0.1:8080/GetData%22, outputFile)
When the file is received, the FileReceived event is called, which you will need to implement so you know when the file download has finished.
Posting to a Form
To post data to a form on a page, you first build the form text and then use the SetRequestContent method to specify it. Then you can call the Send method to send the request. Here is an example that sends a POST request with form data:
Dim formText As String = "firstName=Bob&lastName=Roberts"
// POST it
iOS projects use Xojo.Net.HTTPSocket for HTTP communication. This class works similarly to URLConnection.
iOS and Mac Notes
On iOS and Mac you will not be able to send requests to non-secure URLs. Apple calls this App Transport Security. That is only "https" URLs are allowed by default. If you need to call an "http" URL you will need to provide a plist with your app that is configured to allow these type of URLs. Refer to the UserGuide:App Transport Security topic for more information.