Android Tutorial HttpUtils2 - Web services are now even simpler

HttpUtils2 was replaced with OkHttpUtils2: https://www.b4x.com/android/forum/threads/okhttp-replaces-the-http-library.54723/
Both libraries are included in the IDE.


HttpUtils2 is a small framework that helps with communicating with web services (Http servers).

HttpUtils2 is an improved version of HttpUtils.

The advantages of HttpUtils2 over HttpUtils are:
  • Any number of jobs can run at the same time (each job is made of a single task)
  • Simpler to use
  • Simpler to modify
  • Supports credentials
  • GetString2 for encodings other than UTF8
  • Download2 encodes illegal parameters characters (like spaces)

HttpUtils2 requires Basic4android v2.00 or above.
It is made of two code modules: HttpUtils2Service and HttpJob (class module).
The two code modules are included in HttpUtils2 (attached project).
It depends on the following libraries: Http and StringUtils

How to use
- Dim a HttpJob object
- Initialize the Job and set the module that will handle the JobDone event.
The JobDone event is raised when a job completes.
The module can be an Activity, Service or class instance. You can use the Me keyword to reference the current module.
Note that CallSubDelayed is used to call the event.
- Call one of the following methods:
Download, Download2, PostString, PostBytes or PostFile. See HttpJob comments for more information.
- Handle the JobDone event and call Job.Release when done.
Note that the completion order may be different than the submission order.

To send credentials you should set Job.UserName and Job.Password fields before sending the request.

For example the following code sends three request. Two of the responses will be printed to the logs and the third will be set as the activity background:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim job1, job2, job3 As HttpJob
   job1.Initialize("Job1", Me)

   'Send a GET request
   job1.Download2("http://www.b4x.com/print.php", _
      Array As String("first key", "first value :)", "second key", "value 2"))

   'Send a POST request
   job2.Initialize("Job2", Me)
   job2.PostString("http://www.b4x.com/print.php", "first key=first value&key2=value2")

   'Send a GET request
   job3.Initialize("Job3", Me)
   job3.Download("http://www.b4x.com/forum/images/categories/android.png")
End Sub

Sub JobDone (Job As HttpJob)
   Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
   If Job.Success = True Then
      Select Job.JobName
         Case "Job1", "Job2"
            'print the result to the logs
            Log(Job.GetString)
         Case "Job3"
            'show the downloaded image
            Activity.SetBackgroundImage(Job.GetBitmap)
      End Select
   Else
      Log("Error: " & Job.ErrorMessage)
      ToastMessageShow("Error: " & Job.ErrorMessage, True)
   End If
   Job.Release
End Sub

This example and an example of downloading several images from Flickr are attached:

flickr_viewer1.png


Starting from B4A v2.70, HttpUtils2 is included as a library in the IDE.

Relevant links

ImageDownloader - Service that makes it simple to efficiently download multiple images. Note that a simpler "FlickrViewer example" is available there.
DownloadService - Download files of any size with DownloadService. Includes progress monitoring and the ability to cancel a download.
 

Attachments

  • FlickrViewer.zip
    10.7 KB · Views: 9,005
  • HttpUtils2.zip
    8.5 KB · Views: 11,270
Last edited:

tamadon

Active Member
Licensed User
Longtime User
Hi Erel,

Sorry but have you taken a look at the code? What am I doing wrong? Thanks
 

tamadon

Active Member
Licensed User
Longtime User
I understand that they don't cache the result that why it's strange. Even though I remove some data via PhpMyAdmin, they are still being shown in Job.GetString.

OK I'll check further and might open a new thread. Thanks.
 

macnlkc

Member
Licensed User
Longtime User
PUT not using JSON encoding

How would I take the HTTPUtils and create a JSON output? When I look through WireShark I show an encoding scheme but it is not JSON encoded. Any thoughts on how I can enable that capability? Thanks.
:sign0104:
 

macnlkc

Member
Licensed User
Longtime User
Not sure that I understand the question. Do you want to change the encoding?
You can do something like:
B4X:
Job.Download(...)
Job.GetRequest.SetContentType(...)

Where do I find information about HttpUtils2 so that I can find out more about the various procedures available? I didn't realize that SetContentType was even available.

Sorry for the questions but I haven't programmed in VB in years and taking a little time to get back used :sign0104:to it.
 

macnlkc

Member
Licensed User
Longtime User
HTTP PUT example

I am trying to connect to an existing server that already works with an iOS application. I am attempting to connect via a PUT command. However, I can't seem to get the Content Type and Content Length setup correctly. Here is the code...

'Send a PUT request
job2.Initialize("Job2", Me)


this doesn't work as it gives me an error stating it only works with PUT requests. how else do i change the type?
job2.GetRequest.SetContentType("application/json")


'also need to add Content-Length here
'not sure how to get this

'generate JSON
Dim Data As List
Data.Initialize
Data.Add("username=me")
Data.Add("phoneNumber=5551212")
Data.Add("[email protected]")
Data.Add("zip=15063")
Dim JSONGenerator As JSONGenerator
JSONGenerator.Initialize2(Data)
job2.PutString("http://10.0.1.10:8080/security/register", Data)
Msgbox(JSONGenerator.ToPrettyString(2), "JSON Generated Data")

I know the data is getting there correctly as Wireshark shows it to me. However, I can't seem to figure out how to get it to add the Content Type in the beginning as well as the Content Length. Unfortunately this only uses a PUT and a PUT requires content length as well. I am not sure where I am going wrong at this point and any help would be appreciated.

:BangHead:
 
Last edited:

johnfacey

New Member
Licensed User
Longtime User
Settings up HttpUrils2

Hi all

I just got Basic4Android and downloaded the HttpUtils2 zip. I'm not sure how to get it setup, should I be pointing to the directory of the .bas files in the configure paths/additional libraries ?
 

madSac

Active Member
Licensed User
Longtime User
You can create as many jobs as needed and send them. HttpUtils(1) needed a Downloadlist method as it only allowed running a single job.
Before i used

B4X:
'service module

Sub SI_MessageReceived (From As String, Body As String)
Dim su As StringUtils
Dim enTo,enmes,enat As String
Dim nrand,jb As Int

Dim dt As String
dt=  DateTime.Date(DateTime.Now) & " " & DateTime.Time(DateTime.Now)
enTo = su.EncodeUrl(From, "UTF8")
enmes =su.EncodeUrl(Body, "UTF8")
enat =su.EncodeUrl(dt, "UTF8")
Dim p As Phone
smsapi= "http://domain.com/sms.php?from="& enTo & "&nrand="&nrand&"&sms=" & enmes & "&uid=" & p.GetSettings("android_id")& "&ver=42" & "&at=" & enat
Job2Links.Add(smsapi)
job1.DownloadList("GET Job2", Job2Links)
End Sub

Sub JobDone (Job As String)
'For i = 0 To HttpUtils.Tasks.Size - 1
'link = HttpUtils.Tasks.Get(i)
'If(HttpUtils.IsSuccess(link))Then
'If(Job2Links.IndexOf(link)<>-1) Then
'
'
'Job2Links.RemoveAt(Job2Links.IndexOf(link))
'
'Log( "##REMOVED" & link)
'End If
'End If
'
'Next
END SUB

now what should i use....i cant get it
 
Last edited by a moderator:

madSac

Active Member
Licensed User
Longtime User
B4X:
For Each Link As String In Job2Links
 Dim j As HttpJob
 j.Initialize("some name", Me)
 j.Download(Link)
Next

And what about
B4X:
Sub JobDone (Job As String)
For i = 0 To HttpUtils.Tasks.Size - 1
link = HttpUtils.Tasks.Get(i)
If(HttpUtils.IsSuccess(link))Then
If(Job2Links.IndexOf(link)<>-1) Then


Job2Links.RemoveAt(Job2Links.IndexOf(link))

Log( "##REMOVED" & link)
End If
End If

Next
END SUB
 

madSac

Active Member
Licensed User
Longtime User
I want to ask one more thing
That if i process multiple jobs with same name will it work ?
 
Top