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

Cadenzo

Active Member
Licensed User
Longtime User
Everything works fine with the sample from the file "HttpUtils2.zip". (Thanks for this great think, Erel!)

Now I send a string via post to the server and want to get the response-string:
job1.PostString("http://... ...aspx", "test! <> ssad sad#+fdädf+ü fdgü+sgffsdg")

The response arrives ok, but when I want to put it to a string:
Dim sResponse As String = job1.GetString

...I get this error:
tr.Initialize2(File.OpenInput(HttpUtils2Service.TempFolder, taskId), Encoding)

With a breakpoint I could not see, that the method "Service_Create" in the Service-Modul, where the TempFolder is initialized is fired.

What I am doing wrong?
Greetings and thanks for help
Heiko
 

Cadenzo

Active Member
Licensed User
Longtime User
Sorry, it was my stupidity. I did the job1.GetString just after the job1.PostString(...) and not in the JobDone-Methode. Now everything works fine, thanks! :)
 

ArminKH

Well-Known Member
how is possible to show an image which downloaded by using httputils (show by gallery - intent)?
i want when my download finished then my downloaded image show by gallery
tnx
 

DonManfred

Expert
Licensed User
Longtime User
gives an error.
1. Create a new thread in the questions forum;Not here in the tutorials-section) for your problem and
2. Give us more informations! Starting with the exact error-message... Just say i get an error is the wrong way to ask for help!! Show us your code and use code tags when posting code
 

Digital911

New Member
Licensed User
Longtime User
Is there any possibility of re-working this class to use threading/doevents (or something else) vs a service. I've tried using doevents in a loop after calling the "job.download2" but it doesn't seem to want to proceed to create/run the service until the calling sub is exited. I would like to wait in the same calling sub for the response before proceeding cause I need to continue other http calls and it become a big web if I have to break it into calling the next code from the "JobDone" and then from the next "JobDone", etc. vs something like this:

'Note: add a "done" flag to the job class that gets set in the "CompleteJob" sub
job.download2...
while waiting for job to finish
doevents
loop
job.download2...
while waiting for job to finish
doevents
loop
etc...

Thanks in advance for your suggestions.
 

fransvlaarhoven

Active Member
Licensed User
Longtime User
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

Hallo Erel,

I have the same problem that needs the same solution but i dit not find the location for downloading the HttpUtils2 modules.
Can you help me with this?

Thanks,
 

JeanEngelbrecht

New Member
Licensed User
Longtime User
Hi,

I am quite new to Basic4Android and my java experience is basically none.

When I try to compile my app I get the following proplem.

B4A line: 54
Log(Response.GetString(\
javac 1.8.0_60
src\anywheresoftware\b4a\samples\flickr\httputils2service.java:144: error: cannot access ParseException
anywheresoftware.b4a.keywords.Common.Log(_response.GetString("UTF8"));
^
class file for org.apache.http.ParseException not found

Can someone please help me?

From my understanding I need to add httpcore-4.2, but I don't know how or where.
 

Florin

Member
Licensed User
Longtime User
Hi,
For some time now I try to find a way to upload a file to a server, works great with HTML, never with B4A. Please help.
Find below the codes for html, php and b4a, which I have simplified to maximum in order to get some positive results ...


HTML:

<!DOCTYPE html>
<html>
<body>
<form action="upload2.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>


PHP: upload2.php

<?php
$target_dir = "kp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>



B4A:
SubButPostFile_Click
job2.Initialize("Job2",Me)
job2.PostFile("http://www.xxxxxxx.yy/upload2.php", File.DirRootExternal, "p.jpg")
EndSub
 

aedwall

Active Member
Licensed User
Longtime User
I loaded this project and it will not compile:

B4A version: 5.50
Parsing code. (0.00s)
Compiling code. (0.04s)
Compiling layouts code. (0.00s)
Generating R file. (0.04s)
Compiling debugger engine code. (0.56s)
Compiling generated Java code. Error
B4A line: 16
hc.Initialize(\
javac 1.8.0_66
src\anywheresoftware\b4a\samples\httputils2\httputils2service.java:222: error: cannot access ClientProtocolException
_hc.Initialize("hc");
^
class file for org.apache.http.client.ClientProtocolException not found

What do I need to do to fix this? Thank you.
 
Top