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,161
  • HttpUtils2.zip
    8.5 KB · Views: 11,482
Last edited:

CharlesIPTI

Active Member
Licensed User
Longtime User
Hi, I'm new programmer.
I wonder if there is a way to fill a field on a webpage and receive the response of the new page?
Ex: A search on GOOGLE.

I did this using the library Selenium in JAVA.

Thank you.

You just gotta love these Right >> ??
:sign0161::sign0161::sign0161:
 

sally3599

Member
Licensed User
Longtime User
Unknown type: httprequest when use HttpUtils2

I just copy HttpJob.bas, HttpUtils2Service.bas and Add Existing Module, but it display these error message when compile:

B4X:
Compiling code.                         Error
Error parsing program.
Error description: Unknown type: httprequest
Are you missing a library reference?
Occurred on line: 11
Private req As HttpRequest

Anything wrong?

but compile the example HttpUtils2.zip is no problem, any suggestion?
 
Last edited:

admac231

Active Member
Licensed User
Longtime User
I just copy HttpJob.bas, HttpUtils2Service.bas and Add Existing Module, but it display these error message when compile:

B4X:
Compiling code.                         Error
Error parsing program.
Error description: Unknown type: httprequest
Are you missing a library reference?
Occurred on line: 11
Private req As HttpRequest

Anything wrong?

but compile the example HttpUtils2.zip is no problem, any suggestion?

You need to reference the HTTP library and the StringUtils library.

Click on the "Libs" tab at the bottom-right and check the boxes beside these two.
 

AndyMinsk

New Member
Licensed User
Longtime User
Hi. I use the next function to download the page:
B4X:
'... some of code here 
Sub GetIssues
   ProgressDialogShow("Loading list of issues...")
   Dim job1 As HttpJob
   job1.Initialize("Job1", Me)
   job1.Download(ServerAddr & "/issues.xml?key=" & SecretKey)
End Sub

Sub JobDone (Job As HttpJob)
   ProgressDialogHide
   If Job.Success = True Then
      in = Job.GetInputStream
      Log(Job.GetString)
      parser.Parse(in, "Parser") 'programm crashes here
   End If
End Sub

After calling GetIssues I successfully download the page (Job.GetString returns me valid page content). After that, programm crashes on the parser.Parse(in, "Parser") string with the next message:
B4X:
LastException java.lang.NullPointerException]
How to solve this problem?
 
Last edited:

AndyMinsk

New Member
Licensed User
Longtime User
Hi. I use the next function to download the page:
B4X:
'... some of code here 
Sub GetIssues
   ProgressDialogShow("Loading list of issues...")
   Dim job1 As HttpJob
   job1.Initialize("Job1", Me)
   job1.Download(ServerAddr & "/issues.xml?key=" & SecretKey)
End Sub

Sub JobDone (Job As HttpJob)
   ProgressDialogHide
   If Job.Success = True Then
      in = Job.GetInputStream
      Log(Job.GetString)
      parser.Parse(in, "Parser") 'programm crashes here
   End If
End Sub

After calling GetIssues I successfully download the page (Job.GetString returns me valid page content). After that, programm crashes on the parser.Parse(in, "Parser") string with the next message:
B4X:
LastException java.lang.NullPointerException]
How to solve this problem?

Oh, I forget to initialize my parser. Now it's work well. I can't find error in two hours, but after posting code to a forum I find it in five minutes!
 

DannyRyan

Member
Licensed User
Longtime User
Hi, i am new to using b4a - i have VBA experience already, however finding some of the functions a little difficult to grasp at the moment.
I am looking to download the source of a webpage using the httputils2 service module.

I have the service & class modules in my project and can run the example provided, but i am unable to show the contents of a given webpage

for example i know using the HttpRequest.request i can do this. but the messing around with the hc_ResponseSuccess (as shown in the JSON examples) is not pretty.

I was wondering if i could use httpUtils2 which is much neater to do the same thing?

Any help it greatly appreciated.

:sign0085:

UPDATE:
I figured it out, so i am posting here - in case anyone else asks the same question.

Sub Activity_Create(FirstTime As Boolean)
Dim job4 As HttpJob
job4.Initialize("Job4",Me)
job4.Download("http://www.google.co.uk")
.......
End
.......
End Sub


Sub JobDone (Job As HttpJob)
If Job.Success = True Then
Msgbox(Job.GetString,"")
......
End if
......
End Sub
 
Last edited:

qsrtech

Active Member
Licensed User
Longtime User
New Addition to HTTP Service

Hi Guys, thought this little modification might help out with using this great service.

Update the Initialize routine in the HTTPJob class:

Public Sub Initialize (Name As String, TargetModule As Object,Event As String)
JobName = Name
target = TargetModule
'new
If Event="" Then Event="JobDone"
EventName=Event
End Sub

Update the Complete routine in the HTTPJob Class:

Public Sub Complete (id As Int)
taskId = id
CallSubDelayed2(target, EventName, Me)
End Sub

You can now initialize a Job class and use a specific sub to handle a specific job.

John

EDIT: You will need to Dim a new HTTPJob class for each job i.e.

Dim http as HTTPJob
http.initialize(....)
 
Last edited:

qsrtech

Active Member
Licensed User
Longtime User
httpjob.download(url) with space in url issue

Hi,

I'm getting an error when trying to download an image file that contains a space in the name. Can someone please suggest a workaround.

B4X:
http.Initialize("getImage",Me,"ImageDone")
'value may contain a space character
'tried these w/o success
'value=su.EncodeUrl(value,"UTF8")
'value=value.Replace(" ","%20")
http.Download(value)
Thanks!
John
 

qsrtech

Active Member
Licensed User
Longtime User
HTTP link error/http job limitations

Ok I'll try that one more time. Do you know if there are any limitations to the number of concurrent http jobs that can run? Cause when I'm grabbing hundreds of icons from my webserver (i.e. creating hundreds of http jobs to download the PNG files only a few jobs actually get completed. I know my phone (S2) is limited to only 8 open browser windows.

basic procedures(overly simplistic):
sub loop through icon list
create button
assign properties
create httpjob to grab icon
end sub

sub Jobdone
job.getbitmap
assign bitmap to button
job.release
end sub

Note: in the mean time, my work around is to just fetch the next image when the job is done, thereby only having one job at a time, i.e.

sub loop through icon list
create button
assign properties
build joblist
when all buttons are created, startfirstjob(joblist(0))
end sub

sub jobdone
job.getbitmap
assign bitmap to button
joblist.removeat(0)
fetch next joblist(0)
end sub

Thanks!
John
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Do you know if there are any limitations to the number of concurrent http jobs that can run? Cause when I'm grabbing hundreds of icons from my webserver (i.e. creating hundreds of http jobs to download the PNG files only a few jobs actually get completed.
There is no limit. All files should eventually be downloaded. However sending hundreds of requests may slow down the process.
 

tamadon

Active Member
Licensed User
Longtime User
Hi, I've just started playing with HTTPUtils 2. I am retrieving a simple online scoreboard data from my web server. Everything works fine except when I add a new scores and try retrieving again, the new scores are not included.

I've checked with phpMyAdmin and indeed the new score data have been entered correctly.

What am I missing?
 

tamadon

Active Member
Licensed User
Longtime User
Hi Erel,

I am attaching the online score sample project. It was created using normal HTTP before I tried using HttpUtils2.

You can add new score then when you try listing the score again, the new score is not included in the list. Currently the result is output to the log.

You can download the sample project here:

http://removed

Thanks for your help
 
Last edited:

macnlkc

Member
Licensed User
Longtime User
HTTP PUT Example

Is there an example of an HTTP PUT function? I can see the POST and GET operations but was wondering if the HTTPUtils2 had a PUT example as well?

:sign0104:
 
Top