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

walterf25

Expert
Licensed User
Longtime User
HTTP multiple requests

Hi Erel, i'm updating one of my apps and i need to figure out a way to make multiple HTTP requests one after the other, there's sometimes where I will need to make up to 16 requests, i tried to do this last night but i keep getting the "main page could not load" error.
I got it to work if i set a timer and assign each request to run inside a timer but this takes way too long, so i need to figure out a way to make those requests faster.
A little background about my app.
I have a database which has around 20,000 records in it, at first i use the GPS library to locate the user's current location and then i look at the database and see if the user's location is within a few meters from any of the coordinates in the database once it finds a close location then i send an HTTP request, this is for a Local Transportation bus schedule app that i made, this update is so that when the user opens the app it automatically detects his/her location and gives him a schedule of the bus stops near him/her, as you can imagine, if there's around 10 bus stops near by there will be 10 http requests.
So how can i handle this?

Thanks Erel!
 

Smee

Well-Known Member
Licensed User
Longtime User
I have a small problem trying to remove items from a list.
The code is as follows

B4X:
Sub JobDone (Job As HttpJob)
If Job.Success = True Then
Select Job.JobName

Case "Job3"
DownloadFiles(Job.GetString)
..
..
   Job.Release
End Sub

Sub DownloadFiles (st As String)
'Dim ListFiles As List
ListFiles = s.Split(st,Chr(13)&Chr(10))
...
..
..
..

ListJpegs.RemoveAt(1)
End Sub

When the program hits the Remove at line i get the error
java.lang.UnsupportedOperationException

Can you tell me what is wrong with this line or how i can remove certain items?

Many thanks for the great code
 

Smee

Well-Known Member
Licensed User
Longtime User
String.Split returns a read-only list. You should use this code:
B4X:
ListFiles.AddAll(s.Split(...))

Note that the first index is 0 not 1.

Many thanks Erel,
yeah i know about the first index, it was just an example, i may need to remove at random locations. and i know i have to remove from the top first. many thanks again.
 

AllanD

Member
Licensed User
Longtime User
getting Already working. Request ignored when using httputils2

Hello,
I am getting an error when using the httputils. The log says Already "working. Request ignored" when attempting to run a job.

It is a possing sort of activity so a connection to the servis made a few times and then stop working.

Is httputils2 the latest library, has it been replaced?

What can I do?
 

AllanD

Member
Licensed User
Longtime User
getting Already working. Request ignored when using httputils2

I am sorry folks, I was using the old version and not httputils2. After upgrading all is well:sign0060:
 

tutecnicodavid

Member
Licensed User
Longtime User
httupultis 2 problem

My problem is that if I throw several postString not seem to follow the order of execution, ie it can end up in different order or even not finishing started ... it can not be synchronized to work with the order in which they call?

My code is something like this:

1.- C1.PostString("http://" & Main.IPServidor & "/mabe/guardar_control_entrada.php?numero_partida=" & NumeroPartida & "&observaciones=" & s.EncodeUrl(txtObservaciones.Text,"UTF8") & "&id_usuario=" & s.EncodeUrl(Main.CodigoUsuario,"UTF8"),"")

2.- C2.postString("http://"& Main.IPServidor &"/mabe/actualizar_control_entrada.php?id_control_entrada=" & txtNumeroControl.Text & "&numero_partida=" & NumeroPartida & "&observaciones=" & s.EncodeUrl(txtObservaciones.Text,"UTF8"),"")

3.- For i=0 To TotalMedidasBrix-1
If ListaMedidaBrix(i).Text<>0 AND ListaMedidaBrix(i).Text<>"" Then
C(i).Initialize("insertarmedidascontrolentrada",Me) C(i).PostString("http://"& Main.IPServidor & "/mabe/insertar_medida_control_entrada.php?id_control_entrada=" & txtNumeroControl.Text & "&medida_brix=" & s.EncodeUrl(ListaMedidaBrix(i).Text,"UTF8"),"")
End If
Next

but instead of ending 1, 2 and 3 ... I think that overlap and chace give an error and does not generate the records in the database whenever.

Please say Aguien know help me: Sign0085:
 

stevel05

Expert
Licensed User
Longtime User
Have you tried using the JobDone callback and starting the next job when the previous one has finished?
 

tutecnicodavid

Member
Licensed User
Longtime User
jobdone callback

I do not understand what you mean with "JobDone callback" ... could you give me an example? Thanks and sorry my ignorance: Confundido:
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Http requests are executed asynchronously. So if you submit several jobs the completion order is not deterministic. You can use Job.JobName to find out which Job has just completed (in JobDone). If you really need to send the next job only after the previous one has completed then you should submit the next job from JobDone.
 

javiers

Active Member
Licensed User
Longtime User
Error with HttpJob...

Hello
I use the following code to get an image and then save it.

Dim job As HttpJob
job.Initialize ("000", Me)
job.Download ("https://www.fnmoc.navy.mil/wxmap_cgi/dynamic/NVG/current/nvg10.tas.000.europe2.png")

I get the following error:

Error: javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

Any solutions?

Thanks
 

javiers

Active Member
Licensed User
Longtime User
Thanks. Solved.

Thanks Erel.
work properly with your answer.:icon_clap:

A greeting
 

NFOBoy

Active Member
Licensed User
Longtime User
So, I am using HTTPUtils2, and it works great, even easier than I expected, as it took me two hours to realize how easy it was to get a bmp downloaded from a link. (I was trying to figure out how to tell the the job it was a bmp so it could be put into an imageview, vs a page of text, but that's done auto-magically!)

In fact, that's my question, How is that done? I have looked through the Httpjob and HttpUtils2 code, and can follow what is happening in there. (at least I think I do) The Service runs an asynchronous request when the HTTPClient says it was successful, and saves the data to the TempFolder (whatever was retrieved), which is then assigned to the instantiated job. But I'm not seeing how the job knows what it was? Is that all based on the page that was requested?

If this is something basic I should understand, can you point me to where I can read up on it?

Ross
 
Top