Android Programming Press on the image to return to the main documentation page.

HTTP

The HTTP library allows you to communicate with web services and to download resources from the web.
As network communication can be slow and fragile this library handles the requests and responses in the background and raises events when a task is ready.
There are two HTTP examples which demonstrate this library:
Currency Converter and a more complex example: Flickr Viewer.

List of types:

HttpClient
HttpRequest
HttpResponse

HttpClient

The main object. This object can manage multiple tasks concurrently. It is very important to declare it as a process global variable (under Sub Process_Globals).
A typical example of downloading a string:
 
Sub Process_Globals
    
Dim hc As HttpClient
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    
If FirstTime Then
        hc.Initialize(
"hc")
    
End If
    
Dim req As HttpRequest
    req.InitializeGet(
"http://www.basic4ppc.com/")
    hc.Execute(req, 
1)
End Sub

Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    
Dim resultString As String
    resultString = Response.GetString(
"UTF8")
    
'Work with the result
End Sub

Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    Log(
"Error connecting: " & Reason & " " & StatusCode)
    
If Response <> Null Then
        Log(Response.GetString(
"UTF8"))
        Response.Release
    
End If
End Sub

Permissions:

android.permission.INTERNET

Events:

ResponseSuccess (Response As HttpResponse, TaskId As Int)
ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)

Members:


  Execute (HttpRequest As HttpRequest, TaskId As IntAs Boolean

  ExecuteCredentials (HttpRequest As HttpRequest, TaskId As Int, UserName As String, Password As StringAs Boolean

  Initialize (EventName As String)

  InitializeAcceptAll (EventName As String)

  SetHttpParameter (Name As String, Value As Object)

  SetProxy (Host As String, Port As Int, Scheme As String)

Members description:

Execute (HttpRequest As HttpRequest, TaskId As IntAs Boolean
Executes the HttpRequest asynchronously. ResponseSuccess or ResponseError events will be fired later.
Note that in many cases the Response object passed in ResponseError event will be Null.
If there is a request with the same TaskId already running then this method will return False and the new request will not be submitted.
ExecuteCredentials (HttpRequest As HttpRequest, TaskId As Int, UserName As String, Password As StringAs Boolean
Same behavior as Execute. The UserName and Password will be used for Basic or Digest authentication.
Digest authentication is only supported for GET requests.
Initialize (EventName As String)
Initializes this object.
IMPORTANT: this object should be declared in Sub Process_Globals.
EventName - The prefix that will be used for ResponseSuccess and ResponseError events.
InitializeAcceptAll (EventName As String)
Similar to Initialize, with one important difference. All SSL certificates will be automatically accepted.
This method should only be used when trying to connect to a server located in a secured network.
SetHttpParameter (Name As String, Value As Object)
Sets the value of the parameter with the given name.
SetProxy (Host As String, Port As Int, Scheme As String)
Sets the proxy to use for the connections.
Host - Proxy host name or IP.
Port - Proxy port.
Scheme - Scheme name. Usually "http".

HttpRequest

Holds the target URL and other data sent to the web server.
The initial time out is to 30000 milliseconds (30 seconds).

Events:

None

Members:


  InitializeDelete (URL As String)

  InitializeGet (URL As String)

  InitializeHead (URL As String)

  InitializePost (URL As StringInputStream As java.io.InputStream, Length As Int)

  InitializePost2 (URL As String, Data() As Byte)

  InitializePut (URL As StringInputStream As java.io.InputStream, Length As Int)

  InitializePut2 (URL As String, Data() As Byte)

  RemoveHeaders (Name As String)

  SetContentEncoding (Encoding As String)

  SetContentType (ContentType As String)

  SetHeader (Name As String, Value As String)

  Timeout As Int  [write only]

Members description:

InitializeDelete (URL As String)
Initializes the request and sets it to be a Http Delete method.
InitializeGet (URL As String)
Initializes the request and sets it to be a Http Get method.
InitializeHead (URL As String)
Initializes the request and sets it to be a Http Head method.
InitializePost (URL As StringInputStream As java.io.InputStream, Length As Int)
Initializes the request and sets it to be a Http Post method.
The specified InputStream will be read and added to the request.
InitializePost2 (URL As String, Data() As Byte)
Initializes the request and sets it to be a Http Post method.
The specified Data array will be added to the request.
Unlike InitializePost this method will enable the request to retry and send the data several times in case of IO errors.
InitializePut (URL As StringInputStream As java.io.InputStream, Length As Int)
Initializes the request and sets it to be a Http Put method.
The specified InputStream will be read and added to the request.
InitializePut2 (URL As String, Data() As Byte)
Initializes the request and sets it to be a Http Put method.
The specified Data array will be added to the request.
RemoveHeaders (Name As String)
Removes all headers with the given name.
SetContentEncoding (Encoding As String)
Sets the encoding header of the request.
This method should only be used with Post or Put requests.
SetContentType (ContentType As String)
Sets the Mime header of the request.
This method should only be used with Post or Put requests.
SetHeader (Name As String, Value As String)
Sets the value of the first header with the given name. If no such header exists then a new header will be added.
Timeout As Int  [write only]
Sets the request timeout measures in milliseconds.

HttpResponse

An object that holds the response returned from the server.
The object is passed in the ResponseSuccess event.
You can choose to read the response synchronously or asynchronously.
It is important to release this object when it is not used anymore by calling Release.

Events:

StreamFinish (Success As Boolean, TaskId As Int)

Members:


  ContentEncoding As String  [read only]

  ContentLength As Long  [read only]

  ContentType As String  [read only]

  GetAsynchronously (EventName As String, Output As java.io.OutputStream, CloseOutput As Boolean, TaskId As IntAs Boolean

  GetHeaders As Map

  GetInputStream As InputStreamWrapper

  GetString (DefaultCharset As StringAs String

  Release

  StatusCode As Int  [read only]

Members description:

ContentEncoding As String  [read only]
Returns the content encoding header.
ContentLength As Long  [read only]
Returns the content length header.
ContentType As String  [read only]
Returns the content type header.
GetAsynchronously (EventName As String, Output As java.io.OutputStream, CloseOutput As Boolean, TaskId As IntAs Boolean
Asynchronously reads the response and writes it to the given OutputStream.
If there is a request with the same TaskId already running then this method will return False, and the response object will be released.
The StreamFinish event will be raised after the response has been fully read.
EventName - The sub that will handle the StreamFinish event.
Output - The stream from the server will be written to this stream.
CloseOutput - Whether to close the specified output stream when done.
TaskId - The task id given to this task.
Example:
Sub Http_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    Response.GetAsynchronously(
"ImageResponse", _ 
        File.OpenOutput(File.DirInternalCache, 
"image.jpg", False), True, TaskId)
End Sub

Sub ImageResponse_StreamFinish (Success As Boolean, TaskId As Int)
    
If Success = False Then
        Msgbox(LastException.Message, 
"Error")
        
Return
    
End If
    ImageView1.Bitmap = LoadBitmap(File.DirInternalCache, 
"image.jpg")
End Sub
GetHeaders As Map
Returns a Map object with the response headers.
Each elements is made of a key which is the header name and a value which is a list containing the values (one or more).
Example:
Dim list1 As List
list1 = response.GetHeaders.Get(
"Set-Cookie")
For i = 0 To list1.Size - 1
    Log(list1.Get(i))
Next
GetInputStream As InputStreamWrapper
Returns the InputStream that you can use to read the response.
GetString (DefaultCharset As StringAs String
Reads the response and returns it as a string.
The specified encoding will be used if the response did not define it explicitly.
Example:
Dim result As String
result = HttpResponse1.GetString(
"UTF8")
Release
Frees resources allocated for this object.
StatusCode As Int  [read only]
Returns the response Http code.
Top