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

doomer

Member
Licensed User
Longtime User
The code you posted is wrong. It doesn't close the output stream so the file might not be complete.
Something like:
B4X:
Dim out As OutputStream
out = File.OpenOutput(File.DirDefaultExternal,"Test.ini",False )
File.Copy2(job.GetInputStream, out)
out.Close

tnxxxxx again


Doomer ---
 

CharlesIPTI

Active Member
Licensed User
Longtime User
More

HttpUtils requires definition of the callback Activity.
Can this be used in beta 2 in a class serving as a proxy for all of the web service calls. So that it uses HttpUtils and returns the web service results to whatever activity wishes to use it ?
 

CharlesIPTI

Active Member
Licensed User
Longtime User
Answered

Compiling code. Error
Error compiling program.
Error description: An Activity context is required.
This class has a process context.
Adding a global "Activity object" variable will fix this issue.
Occurred on line: 47
HttpUtils.PostString("GetCartState", PostGetCartState,"p_CartNumber=" & 100)
Word: poststring


when attempting to implement HttpUtils in 1.95 CLASS Module

Will I have the same problem with HttpUtils2 ??
Which means you will have to have a HttpUtils JobDone in every Activity that wants to use it .. right


ADDENDUM Tested in 1.95 with NEW HttpUtils2 same error from class module .. so answer = YES !!!

Yes I know I'm odd but I want to call this from a class module and have all of my web service stuff REMOVED
from the activity. Activity One & Two Both call the proxy to the web service. The Proxy handles all this HttpUtil Stuff
Ya know like Normal....
Does anyone else call tons of web service methods for data Up & Down ..?! ?!?!?

When you do this you have to call an Android service. When an Android service is called from Activity_Create the code in Activity_Create will still complete and potentially (your coding) may allow re-entry into Activity_Create...

I have so many preventative Boolean shields in my activity_create I need an excel sheet to keep them sorted. :confused::D :sign0060:
:BangHead:
Same problem with Serial & Bluetooth.

But I believe I have found a way to combine Serial & Bluetooth into a single unit accessible by multiple activities. Maybe ...
 
Last edited:

COBRASoft

Active Member
Licensed User
Longtime User
Multiple POST

Hi Erel,

I haven't got the time to test or read all this, but does v2 support multiple POST at the same time?

Greetings,
Sigurd
 

Inman

Well-Known Member
Licensed User
Longtime User
I upgraded to B4A 2.0. Can I simply replace HttpUtils1 files with HttpUtils2 files and compile or should I make any changes to the calls to HttpUtils, in my own modules?

EDIT:

I glanced through the example in first post and it looks like it is different. I will go through the whole code when I am free.
 
Last edited:

PHB2

Member
Licensed User
Longtime User
I am using the new HttpUtils2 - once I got my head around the changes required it took me a matter of minutes. Worthwhile doing IMO.
 

CharlesIPTI

Active Member
Licensed User
Longtime User
Ahh ha ??

Why do you use the beta version and not v2.00?

With v2.00 it is better to use HttpUtils2. You can use HttpUtils2 from a service or activity and it is much simpler to use it.

So you can't use it from a class though...

The new Class module cannot call HttpUtils2.... Correct ?!?

So what aboutrunning HttpUtil in B4A V2.01/2.01.

I'd like to move my project Up to current B4A version

but I'm obviously not convinced on the the new HttpUtil2.

Can I run HttpUtil in B4A 2.01 & 2.02
as I do my side test projects that attempt to use an android Service as complete host for my Web Services work?
 

invaderwt

Member
Licensed User
Longtime User
HI
i have this link and i read a lot but i don´t know how use your code to conect with my web service.

http://afshow.castrohs.com.br:80/Webserver?wsdl

have something I need do to read this webserver and transalte to a list?


I had wrote anothers programs in java and php i´ve tried wrote a program to android to consume this webserver.
In web I can consume in jave web but use ur basic4 I can´t .

Thanks for anwser my noob question.
Bye
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
The new Class module cannot call HttpUtils2.... Correct ?!?
No, that is not correct.

Can I run HttpUtil in B4A 2.01 & 2.02
Yes. Though for new projects it is recommended to use HttpUtils2 instead.

@invaderwt, you will need to build the XML message and send it with Job.PostString.
There are several similar examples in the forum.
 

CharlesIPTI

Active Member
Licensed User
Longtime User
Tyhank You

Well I'm shocked !! :D


Thanks Erel

I look forward to testing the new class module's access to HttpUtils 2

and once confirmed

-- the new tests for incorporating BlueTooth and serial into a class module accessible by all activities.

Thank you again


:icon_clap: :sign0060: :sign0098:
 

peacemaker

Expert
Licensed User
Longtime User
How to arrange GETting or POSTing several URLs, if results are required one by one?
I mean before a Job had URLs list, now we have independent Jobs of single URL.
 

invaderwt

Member
Licensed User
Longtime User
No, that is not correct.


Yes. Though for new projects it is recommended to use HttpUtils2 instead.

@invaderwt, you will need to build the XML message and send it with Job.PostString.
There are several similar examples in the forum.
thanks I will read again the post and I want understand what i do.
Thanks
 

CharlesIPTI

Active Member
Licensed User
Longtime User
How to arrange GETting or POSTing several URLs, if results are required one by one?
I mean before a Job had URLs list, now we have independent Jobs of single URL.

I don't quite understand this concept peacemaker is describing as I haven't grasped the old URL's list feature, but since the NEW HttpUtils2 is using CallSubDelayed,----
:sign0060: :( :eek:

his question is also VERY Important to me as well.

I assumed that since I need results "GetSetOne" from my web service
before I could create the objects necessary to send as parameters for the next few calls "CombineSetOne_SetTwo" and "SaveSetOne" (generic Examples) that the CallSubDelayed implemented by HttpUtils2 would not be appropriate for my needs.
 

peacemaker

Expert
Licensed User
Longtime User
Thanks, Erel.

Maybe
B4X:
Sub CompleteJob(TaskId As Int, success As Boolean, errorMessage As String)
   Dim job As HttpJob
   job = TaskIdToJob.Get(TaskId)
   TaskIdToJob.Remove(TaskId)
   job.success = success
   job.errorMessage = errorMessage
   job.Complete(TaskId)
   
[B]   taskCounter = taskCounter - 1
   If taskCounter = 0 Then StopService("")[/B]
End Sub

is useful ?
 
Top