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

Martin Larsen

Active Member
Licensed User
Longtime User
Good news: httputils2 does in fact maintain cookies across downloads! There as something wrong with my second call, after the login

But I have a found a new problem with httputils2. If a job fails because of an error such as 404, it's is not possible to get the response string with Job.GetString. This should really be possible since the returned document often explains in more details what's wrong.
 

Martin Larsen

Active Member
Licensed User
Longtime User
1. You can send a HEAD request. How large is the string?

About 120 bytes at most. It's not that it doesn't work with httputils2, it would just be handy with a way to immediate download some data and assign it to a string in one call, just like file_get_contents in php can do.

If Job.Success is true then the response code is 2xx. You can get the status code in hc_ResponseSuccess (or ResponseError) in HttpUtils2Service.

Thanks, I will look into that.

And yes, I found that cookies are indeed maintained, and it works great!

B4A is really awesome :)
 

aeric

Expert
Licensed User
Longtime User
Hi B4A members, I created a sample log in using HttpUtils2 connect to a MySQL table by php script. I want to share it. May I create a new thread in "Tutorials & Examples" to share the code?
 

omidaghakhani1368

Well-Known Member
Licensed User
Longtime User
Hi.
We can use APS.NET web service with url or execute method in url
But in PHP we cannot execute method in url,we must be use soap
Is there any way to use HttpUtil2 to web service and is threre example for php?
 

ilan

Expert
Licensed User
Longtime User
i have a small problem

when i download a file everything is ok but after changing the text on the ftp server i get in job.done the old text and not the updated text

if i put the textfile link in chrome i see the updated text but on my app i get the old text in job.Getstring also after i release the job(job.Release)...

what can i do??
 

ilan

Expert
Licensed User
Longtime User
Did you use the same httpjob or are you DIMming a new one each time?
MAybe show some example code which shows the problem (small testproject)

i use the same
B4X:
       Dim job3 As HttpJob
    job3.Initialize("Job3", Me)
    job3.Download(newftp2 & "/lists/" & link)

should i maybe clear File.DirInternalCache?
 

ilan

Expert
Licensed User
Longtime User
Try using a NEW
B4X:
Dim job3 As HttpJob
each time you start a download. Dont reuse the old object.

this is not working

the thing is that after a while i will get the updates string but not immidiatly after i changed it
maybe something with the ftp server?? (but i can see the new string in google chrome)

this is the link: http://www.sagital.byethost7.com/lists/0504844663.txt

updated string:

ืขื ื‘ื™ื|0004|ืคื™ืจื•ืช ื•ื™ืจืงื•ืช|ื™ื—|9.90| | |C
ื—ืœื‘|0001|ื—ืœื‘, ื‘ื™ืฆื™ื ื•ืกืœื˜ื™ื|ืœื™ื˜ืจ|8.90| | |A

what i get (old string):

ืขื ื‘ื™ื|0004|ืคื™ืจื•ืช ื•ื™ืจืงื•ืช|ื™ื—|9.90| | |A
ื—ืœื‘|0001|ื—ืœื‘, ื‘ื™ืฆื™ื ื•ืกืœื˜ื™ื|ืœื™ื˜ืจ|8.90| | |A
ืžื™ืœืงื™|0002|ื—ืœื‘, ื‘ื™ืฆื™ื ื•ืกืœื˜ื™ื|ื™ื—|2.90| | |B
 

ilan

Expert
Licensed User
Longtime User
if i download the file via ftp i see the new string but with Http job not

this is working:
FTP.DownloadFile("/htdocs/lists/" & LineNumber & ".txt", False, File.DirInternal, LineNumber & ".txt")

this not:
Dim job3 AsHttpJob
job3.Initialize("Job3", Me)
job3.Download(newftp2 & "/lists/" & link)
 

ilan

Expert
Licensed User
Longtime User
now i have deleted the file from my server but its still downloading it (the old string)

there is a chache folder maybe where its downloading from it instead from the ftp server...
 

ValDog

Active Member
Licensed User
Longtime User
I am posting data (JSON) to a server which requires an "authorization header like: Authorization Bearer [your_access_token]."

The relevant code is as follows:

job4.Initialize("Job4", Me)
job4.PostString(PostUrl, gen.ToString)
job4.GetRequest.SetHeader("Authorization Bearer", AccessToken)

When I execute I get:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>

JobName = Job4, Success = false



Am I using the SetHeader method correctly? Any idea what may be my problem, or how to proceed with troubleshooting it?
 

ValDog

Active Member
Licensed User
Longtime User
Yes, you are setting the header correctly.

Can you access this site with another client (browser for example)? If yes then you can monitor the network traffic and see the request that it sends.
I believe I found my problem - thanks!
 

marfonte

New Member
Licensed User
Longtime User
Hi,

How do I call an http verb patch? I need to request an oData update entity

Thanks,
Mario
 
Top