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

walterf25

Expert
Licensed User
Longtime User
HTTPUtils2 help

Hello Erel, I need help, i'm working on this app which up until now everything works great, thanks to this great httputil class.
However when i send this request
I get no error but i get nothing when i try to read with textreader.
I checked the file that gets saved to the SD card and in fact it is empty, i have been trying to figure out all day but i've had no luck, however when i send this other request
and then check the file saved in the sd card i do see the html data.
Can you help me figure this out, when i copy and paste both urls to my browser i can see they both work, but i can't figure out why the first url does not return any information.

Your help will be greatly appreciated Erel.

Cheers,
Walter
 
Last edited:

airblaster

Active Member
Licensed User
Longtime User
Is there any way to activate folding for a Job?
I.e. that only the last request of a certain job name is executed and any prior requests with the same job name are cancelled.
 

airblaster

Active Member
Licensed User
Longtime User
Makes the code a bit more complicated, but I guess this is a viable solution, too.
Implemented it the way you suggested :)
 

ostau

Member
Licensed User
Longtime User
How to pause the app until http-job has finished

I do have a simple task for which I had a pretty complex solution with httputils.
Make three http calls and fill each result into a database table.
There is only one thing to consider:
I have to wait for the end each webcall before the next call may start (because the url for the second call is calculated from the result of the first call (and so on). Now I want to rewrite the code and make it easier to read. I want to use httputils2. Now I do have two problems:

First: the call CallSubDelayed2(...) doesn´t call anything. It simply steps over the line.

Second: With a simple test-app based on the example code of Erel, I didn´t find a way to wait for the end of the first call resp. the second call. It always fires the webcalls parallel and continues with executing the main activity:


My structrue is like this:

Main activity calls a service activity. Service activity uses the httputils2 to place the web calls.

Here are the relevant code snippets, I use

In Activity Main:

Sub CallService(MyJob As String, Param1 As Object)

Dim sparams As List
sparams.Initialize
sparams.Add(MyJob)

CallSubDelayed2(WebService3, "StartJob", sparams)

In ServiceActivity WebService3

Sub Process_Globals
Dim FillBerufsgruppe As HttpJob
....

Sub StartJob (sparams As List)

JobName = sparams.Get(0)
WebServiceUrl = sparams.Get(1)
Parameters = sparams.Get(2)

Select Case JobName

Case "FillBerufsgruppe"
FillBerufsgruppe.Initialize ("Fillberufsgruppe", Me)
FillBerufsgruppe.PostBytes(WebServiceUrl,conv.StringToBytes(Parameters,"UTF-8"))
.......

Sub JobDone (Job As HttpJob)
If Job.Success = True Then
Dim strResult As String
Dim byteResult() As Byte
Dim streamResult As InputStream

strResult = Job.GetString
byteResult = conv.StringToBytes(strResult, "UTF-8")
streamResult.InitializeFromBytesArray(byteResult , 0, byteResult.Length)

Select Job.JobName

Case "FillBerufsgruppe"
InsertIntoDB......
 

mb1793

Member
Licensed User
Longtime User
I have a question, in lines 43-48 what exactly do the case functions do ? what does " images " and "main page" represent ? what are they? .I appreciate all of your help in advance.
 

raaiman

Member
Licensed User
Longtime User
download sth with HTTP OR HttpUtils , how to cancel?

:sign0085::sign0085:

download sth with HTTP OR HttpUtils , how to cancel and pause it?


thanks for reading!
 

ChrShe

Member
Licensed User
Longtime User
Good evening,

Is there a limit to how much can be downloaded?

I'm trying to list videos in a YouTube Channel by downloading the page and using job.getstring to fill a variable which I will then parse.

The thing that I'm running in to is job.getstring only contains a small portion of what I see if I navigate to the page, in I.E. and view source.

Here's basically what I'm doing:
B4X:
Sub Activity_Create(FirstTime as Boolean)
  Dim PageURL as string = "http://www.youtube.com/user/AshevilleHumane/videos?hl=en&gl=US&client=mv-google&sort=dd&view=0&flow=list"

  Dim GetPage as HttpJob
  GetPage.Initialize("GetPageJob", Me)
  GetPage.Download(PageURL)
End Sub
Sub JobDone(Job as HttpJob)
  If Job.Success = True Then
    GetVideoList(Job.GetString)
  Else
    Log("Error: " & Job.ErrorMessage)
  End If
End Sub

"GetVideoList" is where I parse the returned page.

Here is the page that I'm trying to work with:
Happy Flicks - YouTube

It doesn't seem to matter if I use the above page, or the mobile friendly page.

I've attached a txt file that contains all the gets returned by job.GetString.

Any Ideas? or am I missing something?

Thanks much!
~Chris
 

Attachments

  • ReturnedHTML.txt
    4 KB · Views: 400

ChrShe

Member
Licensed User
Longtime User
Ah okay...that makes sense.

My stuff just isn't working because of my still very elementary understanding (or lack there of) of regular expressions. Ha ha!

Many thanks!
~C
 

ChrShe

Member
Licensed User
Longtime User
Oh, okay...yay!!
I will dig into that and let you know how it goes. :)

Thanks again!
 

socialnetis

Active Member
Licensed User
Longtime User
I have an app, in which I display images, and I have a Queue for downloading the next 5 images.
I also intercept the Back button, to ask the user if he wants to quit. If he really wants to quit, the httputils2 service will send a message to a waiting queue, and the service will still be on memory, but I don't need it anymore.
Should I call "StopService", "CancelScheduledService", ExitApplication, or there is some part to cancel this queue that I'm missing?
 

ChrShe

Member
Licensed User
Longtime User
I tried jTidy and SaxParser, SaxParser kept saying that the XML was malformed. :/

No worries though, I found another link to the videos I want, that is much easier to parse. :)

Thanks for the help and the great work!:)
 

lock255

Well-Known Member
Licensed User
Longtime User
Erel I need your help.
I added HttpUtils2Service and HttpJob, but I have not figured out how to connect them to my project. I do not speak English I hope I understand your explanation :)
 
Top