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,523
Last edited:

GMan

Well-Known Member
Licensed User
Longtime User
Error with job (HttpJob)

I tried out this but got always an error.

Heres the error:
tr.Initialize2(File.OpenInput(HttpUtils2Service.Te mpFolder, taskId), Encoding)
(releast in HttpJob)

B4X:
Dim job4 As HttpJob
        job4.Initialize ("Job4", Me)
    job4.Download("http://my.websi.te/app1/version.txt").GetBytes("UTF8")
        NewVersion = job4.GetString 
        MyT.ToastShow ("Act. Version on Server: " & NewVersion,4)
        'other test
        Msgbox(NewVersion,"Version")

the textfile on the server contains i.e. 1.2.3 und ist plain text (UTF8).
All jobs are dim'd and initialized, 3 other jobs work without probs...but they get a webside and a picture...

NewVersion is dimmed as text.

I want to read out the version on server and compare it with the local one.
 

socialnetis

Active Member
Licensed User
Longtime User
Is there a way that the Service raises the event only when you are in the activity that catch it?
I have a problem that If I have two activities, and in Activity 1 I download something, but before the Job_done I go to Activity 2, and if the job finishes, it pulls me back to Activity 1. I think that this is due to CallSubDelayed, but I didn't find any equivalent to what I want
 

exjey

Member
Licensed User
Longtime User
Hello. I need to use the .Download function but the URL containts special characters, meaning a subfolder of the URL path is in language other than english. This cannot be changed to the server, cause many programs (like FTP clients) are sending requests to that path without any kind of problem. I've tried to use the stringutils .encodeurl method but no luck. Can someone help me.

For example, i am trying to .Download a jpg picture from the path:

"http://www.mydomain.com/whatever/(non english chars subfolder name)/my_pic.jpg".

.Download from HttpUtils2 cannot retrieve the picture. If i use a normal english path, it has no problem. So it must be the encoding but i already tried the .EncodeURL method of the StringUtils library.
 

jgbozza

Member
Licensed User
Longtime User
I want to use, for example, job.PostString("http://10.1.1.3/check.asp", "check_update=true") to see if there was any modification in a database in the server.
Then, the server return a formated web page. How to I get to take only the relevant information instead of taking all the headers and html tags?

I am generating the response page, I could post whatever I want from the server to the tablet. Is there a best practice in order to send the information in a "cleaner" way for the tablet to read only what I need?
 
Last edited:

jgbozza

Member
Licensed User
Longtime User
There's database in the tablet that must be syncronized with the database in the server. The tablet works in pooling, each 10 minutes it looks for updates that might have been made.
In positive case, I want the server to return the fields of the new register of the database, so the tablet can read it and update its local database in order to keep a "mirror".
Downloading the database is not a good solution because they are not entirely equal, not no mention that server side is access and tablet side is SQLite.
Basically, when a user enter a new register with COSTUMER, COSTUMER_ID, PHONE_NUMBER and EMAIL, these fields must be sent as a response to a tablet request (using the httputils2).

After a job.poststring("http://10.1.1.6/chk_updt.asp", "check_update=true") the server redirects to another ASP webpage for this specific request with the results within.
 

ashrafidkaidek

Member
Licensed User
Longtime User
Uploadinf txt file

I'm trying to upload a txt file to SkyDrive account by using the following code:
HTML:
   Dim job5 As HttpJob
   Dim Link As String = FolderID & "?access_token=" & AccessToken
   job5.Initialize("Job5", Me)
   job5.PostFile(Link, File.DirInternal, "try.txt")

please note that that Link string is the correct location where the file needs to be uploaded in SkyDrive.

"try.txt" is a file created in "File.DirInternal"

when running the above code I'm getting this error:
-----------------------------------------------------
{
"error": {
"code": "request_header_invalid",
"message": "The header 'Content-Type' is missing the required parameter: 'boundary'."
}
}
JobName = Job5, Success = false
Error: Bad Request
-----------------------------------------------------
Based o Microsoft instructions; this is how this task needs to be done:

POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=A300x

--A300x
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: application/octet-stream

Hello, World!
--A300x--
-----------------------------------------------------


so i'm a little lost here, any idea what's wrong?
.
.
.
 

ashrafidkaidek

Member
Licensed User
Longtime User
Does anybody has a suggestion on what's causing the error described in my previous comment.

if PostFile not the right way to go with SkyDrive then does "Put" method supported here?

here is what Microsoft says:
-------------------------------------------------
For REST, you can use PUT or POST, depending on your platform's recommended approach.

Important On platforms that support the PUT request, PUT should be used to upload files to SkyDrive when possible to avoid errors that can occur when POST is used.

Here's an example of code that uses PUT.

PUT https://apis.live.net/v5.0/me/skydrive/files/HelloWorld.txt?access_token=ACCESS_TOKEN

Hello, World!

--------------------------------------------------
 
Last edited:

GuyBooth

Active Member
Licensed User
Longtime User
Trying to understand the statement "Http2Utils is now included as a library". The examples in the Http2Utils.zip file don't refer to the library at all.
How do I use the libaray? Does it replace the Class? Do I still use the Service?
Sorry, but I'm confused. :sign0085:
 

enrico

Active Member
Licensed User
Longtime User
Http Service

I'd like to modify a project that currently load some images using HttpJob, to use the Service mode, but I can't understand well how to do it.

I have in the Activity :

B4X:
For i = 0 to RecTot - 1
    Dim jobName As String
    jobName = i
    Dim jobImage As HttpJob
    jobImage.Initialize(jobName, Me)
    jobImage.Download(ImageLink(i))
Next

......


Sub JobDone (Job As HttpJob)
    If Job.Success = True Then
        btnImage(Job.jobName).SetBackgroundImage(Job.GetBitmap)
    Else
        'Log("Error: " & Job.ErrorMessage)
        btnImage(Job.JobName).SetBackgroundImage(LoadBitmap(File.DirAssets, "transparent.png"))
        'ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub


Can anybody help with a code sample to put in the Service Module ? Thanks
 

Rusty

Well-Known Member
Licensed User
Longtime User
Is there a way to use the HTTPUtils2 to access a hard drive on a PC within the network?
Thanks,
Rusty
 
Top