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:

Ramanathan Subbiah

New Member
Licensed User
Longtime User
The correct behavior is to reject unknown certificates unless you (the developer) explicitly configure it to accept all certificates.

Follow these steps:
- Uncheck HttpUtils2 library
- Add HttpUtils2 modules (from the first post)
- Check StringUtils and Http libraries
- Change hc.Initialize in HttpUtils2Service to hc.InitializeAcceptAll

Thanks a million Erel. It works now. :)
 

AHilberink

Active Member
Licensed User
Longtime User
The proces is in the background. Is there a way to wait until the proces is completed?

André
 

agus mulyana

Member
Licensed User
Longtime User
Hi Erel,

execuse me, i want to upload something from edit text,, and i use a post string methode, but there is nothing in my web when upload process is finsih, so, if you don't mind, please help me, about that, or anyone have another example, please...thank you
 

lemonisdead

Well-Known Member
Licensed User
Longtime User
i want to upload something from edit text,, and i use a post string methode, but there is nothing in my web when upload process is finsihed
Hello,
Please, have you checked you were getting the data from your EditText ? Have you tried your remote script previously ?
 

agus mulyana

Member
Licensed User
Longtime User
Hello,
Sure, i have checked all data form that (edit text), i mean, how to put my edit text in "Poststring" methode ? thank you
 

lemonisdead

Well-Known Member
Licensed User
Longtime User
i mean, how to put my edit text in "Poststring" methode ?
I am sorry, perhaps don't I unserstand your question but if it is what I do understand, you could :
- get the EditText.Text in a string
- select the proper protocol to use (GET or POST)
- create your Job's request (including eventually the code you need to manage your remote script)

For example, if you use the POST protocol (I do refer to the word "Poststring" you have used), exactly as the sample, Erel provided :
B4X:
Dim MyVar as StringBuilger
MyVar.Append(EditText.Text).Append("OtherCode") ...

'Send a POST request job2.Initialize("Job2", Me)
 job2.PostString("http://www.b4x.com/print.php", MyVar.ToString)
 

agus mulyana

Member
Licensed User
Longtime User
Hello
thank you, but if i according to the previous example, here is :

job2.PostString("http://192.168.0.157/test.php","first key=fisrt value")

but you give me an example different with the above, there is not first key, is that not problem, when i compile my code, and the program tell me if the upload is succes, but, when i check it in my website, the data is not sent correctly..that is missing ...please help me

for this case, i use string builder as you suggested to me

thank you
 

lemonisdead

Well-Known Member
Licensed User
Longtime User
there is not first key
Hello,
Yes there is no "first key" because it is the name of the remote variable you have set inside your remote script. By habits, when I have only one variable, I get one value only. Sorry for the confusion. Erel named the word "variable" a "key" and is right, of course.

The reason why I did use the StringBuilder is because it is (for me) quicker for building strings.

What I mean is, for example, if you have one remote variable (key) named MyVar1, you would construct your request by appending the variable's name and the value using StringBuilder.

MyVar.Append("first_key=").Append(EditText.Text).Append("&Second=").Append.(" ....

And have you checked your script by entering its URL + the variable inside your browser and see if it receives correctly the variable sent ?
192.168.0.157/test.php?key=Value
 

Douglas Farias

Expert
Licensed User
Longtime User
@Erel
its possible to download 2 or + images with http2 ?

B4X:
  'Send a GET request
  job3.Initialize("Job3", Me)
  job3.Download("http://www.b4x.com/forum/images/categories/android.png")

i want to download a small images 10 - 60kb

but is a list of 4 images

www.link1.com/1.jpg
www.link2.com/2.jpg

i m using this to save on png file
B4X:
            Case "baixaimgperfil"
            imgperfil.Bitmap = Job.GetBitmap
            Dim out1 As OutputStream
            out1 = File.OpenOutput(fp,"perfil"&userid&".png", False)
            Job.GetBitmap.WriteToStream(out1,100,"PNG")
            out1.Close

its possible download 4 or 5 images link on the same tame and save this?

Note: Dont is the same link is 4 images with diferent links, i get this links of my database not from a website
 
Last edited:

bluedude

Well-Known Member
Licensed User
Longtime User
Erel,

Any plans to add PUT, DELETE to the library?

If not, how can we get a version 2.01 class which we can adapt to add these methods?

Cheers.
 

bluedude

Well-Known Member
Licensed User
Longtime User
Erel,

I adapted the methods to also work with PUT, DELETE etc. However, I face some problems with json payloads and PUT statements.

When using below JSON it gives me Could not parse invalid json:

{
"field1":"test"
}

I replace the [ and ] because most REST based PUT services don't work with these.

This is what I do:

jsonMap.Put ("field1","test")
jsonList.Add (jsonMap)
json.Initialize2 (jsonList)
jsonData = json.ToPrettyString(2)
'jsonData = jsonData.Replace ("[","")
'jsonData = jsonData.Replace ("]","")

httpPUT.Initialize ("httpPUTResult",Me)
httpPUT.PutString ("some api url",jsonData)
httpPUT.GetRequest.SetContentType("application/json")
 

Douglas Farias

Expert
Licensed User
Longtime User
@Erel its possible send (files) with http2 post?
if yes can show me one exemple?

i see postfile but it send only 1 image, how can i send 2 files?
 
Last edited:

bluedude

Well-Known Member
Licensed User
Longtime User
Erel,

I'm working on an app. but I have some serious problems with httpUtils and the REST services I use. Below the situation:

Encoding that works with my REST service but does not pass B4A httputils
http://www.example.com/test?{"group"%3A"groupa"%2C"merchant"%3A"merchanta"%7D

Non encoded, does not work either with B4A
http://www.example.com/test?{"group":"groupa","merchant":"merchanta"}

Encoding that does not work with my REST but passes B4A httputils
http://www.example.com/test?{"group":"groupa","merchant":"merchanta"}

The last encoded string is not something I can use.

How can I make sure my first string can pass the httpUtils check?
 
Top