Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List Windows Mobile Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

HttpUtils - Android web services are now simple!

Closed Thread
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 05-15-2011, 01:55 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,952
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default HttpUtils - Android web services are now simple!

HttpUtils2 is now available. HttpUtils2 is an improved version and is recommended for new projects.

HttpUtils is made of a code module and a service module. These two modules make it very simple to download online resources and upload data.

The advantages of using HttpUtils are:
  • Much simpler than working with HttpClient directly.
  • Handles parallel calls efficiently and correctly (protects from RejectedExecutionException exceptions).
  • Downloads are not affected by the activity life cycle.
Using HttpUtils

A simple example of downloading a page and returning the page as string:
Code:
Sub Globals
 
Dim b4a As String
 b4a = 
"http://www.basic4ppc.com"
End Sub

Sub Activity_Create (FirstTime As Boolean)
 HttpUtils.CallbackActivity = 
"Main" 'Current activity name.
 HttpUtils.CallbackJobDoneSub = "JobDone"
 HttpUtils.Download(
"Job1", b4a)
End Sub

Sub JobDone (Job As String)
 
Dim s As String
 
If HttpUtils.IsSuccess(b4a) Then
  s = HttpUtils.GetString(b4a)
 
End If
End Sub
First we configure the callback subs. Then we call HttpUtils.Download or HttpUtils.DownloadList. These calls submit a job request to HttpUtils.
A job is made of one or more links.
HttpUtils raises two types of events while processing a job. The UrlDone event is raised for each successful download with the downloaded url and the JobDone event is raised when the whole job finishes.
You cannot submit a new job while a current job is running (though a job can contain many links).

We have three ways to access a downloaded resource:
  • HttpUtils.GetString(Url As String) - Returns the resource as string
  • HttpUtils.GetBitmap(Url As String) - Returns the resource as bitmap
  • HttpUtils.GetInputStream(Url As String) - Returns an InputStream which allows you to manually read the downloaded resource.
These three methods should only be called after the job is done or inside the UrlDone event sub (for that specific Url).
After downloading a resource the Url serves as the key for that resource.

Inside JobDone event sub you should call HttpUtils.IsSuccess before accessing any Url as it is possible that some or all of the downloads have failed. This is not necessary in UrlDone event as UrlDone is called for each successful download.

Second example:
In this example we first download an image and set it as the activity background. Then we download another 6 Urls and print the last one as string. The code for this example is attached.
Code:
Sub Process_Globals
    
Dim ImageUrl As String
    ImageUrl = 
"http://www.basic4ppc.com/android/images/logo2.png"
    
Dim Job2Links As List
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    HttpUtils.CallbackActivity = 
"Main"
    HttpUtils.CallbackJobDoneSub = 
"JobDone"
    HttpUtils.CallbackUrlDoneSub = 
"UrlDone"
    Job2Links.Initialize
    Job2Links.AddAll(
Array As String( _ 
        
"http://www.google.com""http://www.yahoo.com", _
        
"http://www.bing.com""http://www.cnn.com", _
        
"http://www.twitter.com""http://www.facebook.com"))
    
    HttpUtils.Download(
"Job1", ImageUrl)
End Sub

Sub Activity_Resume
    
'Check whether a job has finished while the activity was paused.
    If HttpUtils.Complete = True Then JobDone(HttpUtils.Job)
End Sub
Sub UrlDone(Url As String)
    
Log(Url & " done")
End Sub
Sub JobDone (Job As String)
    
Select Job
        
Case "Job1"
            
If HttpUtils.IsSuccess(ImageUrl) Then 
                
Dim b As Bitmap
                b = HttpUtils.GetBitmap(ImageUrl)
                Activity.SetBackgroundImage(b)
            
End If
            
'Start the second job
            HttpUtils.DownloadList("Job2", Job2Links)
        
Case "Job2"
            
For i = 0 To HttpUtils.Tasks.Size - 1
                link = HttpUtils.Tasks.Get(i)
                
Log(link & ": success=" & HttpUtils.IsSuccess(link))
            
Next
            
If HttpUtils.IsSuccess("http://www.google.com"Then
                
Log(HttpUtils.GetString("http://www.google.com"))
            
End If
    
End Select
    HttpUtils.Complete = 
False 'Turn off the complete flag so we won't handle it again if the activity is resumed.
End Sub
What happens when the user presses on the Home key during a download?
The download will complete successfully (we are using a service for this).
However your activity will be paused and the UrlDone and JobDone events will not fire.

When our activity is resumed we should check if we missed anything. This is done with this code:
Code:
Sub Activity_Resume
    
'Check whether a job has finished while the activity was paused.
    If HttpUtils.Complete = True Then JobDone(HttpUtils.Job)
End Sub
We are calling JobDone ourselves if needed.
In Sub JobDone we reset the Complete flag so we know that this job was handled.
UrlDone event should be considered a "nice to have" feature. Your code should be prepared to handle the case where some UrlDone events were missed due to the activity being paused.

The FlickrViewer example was rewritten and the attached code uses this module.
In this example we first go to the "main" page. In this page we find 9 links to 9 images. We submit a second job with all these links.

We show each image as soon as it is ready by using the UrlDone event.
In JobDone we check if all Urls were handled. We can miss some of these events if the activity was paused during download.




HttpUtils, similar to DBUtils, aims to simplify common tasks that many developers face. The code is available for you. So changes can be made as needed.

Updates:

V1.04 - The service is now destroyed when it is no longer needed and recreated when needed again. This version also fixes a bug that caused the application to crash if the service was started after the process was killed.

V1.02 - PostString, PostBytes and PostFile methods added to HttpUtils.
These methods make it easy to post data to a web service (using http POST method).
The behavior of these methods is similar to Download and DownloadList. JobDone event is raised after the response from the server is read.

The latest version (v1.04) is included in HttpUtilsExample.
Attached Files
File Type: zip FlickrViewer.zip (9.8 KB, 1060 views)
File Type: zip HttpUtilsExample.zip (7.8 KB, 2235 views)
  #2 (permalink)  
Old 05-15-2011, 01:57 PM
Vidar's Avatar
Junior Member
 
Join Date: May 2011
Location: Kempen, Germany
Posts: 31
Default

I love you

Just been playing around with the httpclient.

Thanks for this
  #3 (permalink)  
Old 05-16-2011, 04:31 AM
Senior Member
 
Join Date: Feb 2011
Posts: 489
Default

Fantastic!

Does this mean even if I send a relatively large list of urls (say 50) to HttpUtils, it will handle the queue correctly and download completely while avoiding RejectedExecutionException completely?
  #4 (permalink)  
Old 05-16-2011, 06:19 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,952
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

Quote:
Does this mean even if I send a relatively large list of urls (say 50) to HttpUtils, it will handle the queue correctly and download completely while avoiding RejectedExecutionException completely?
Yes.
  #5 (permalink)  
Old 05-18-2011, 08:50 PM
Junior Member
 
Join Date: May 2011
Posts: 28
Default

I get an error with this:

java.lang.RuntimeException: Error loading Bitmap.

Debugger finds it in HttpUtilsService at

b = LoadBitmap(HttpUtilsService.TempFolder, SuccessfulUrls.Get(URL))

For what it's worth, I got it to run last night on a different emulator, but when I tried to modify the url to a different page, I got an array out of bounds error (I think, I'm going by memory).
  #6 (permalink)  
Old 05-19-2011, 02:09 AM
Junior Member
 
Join Date: May 2011
Posts: 87
Default

I am confused, is this a library?
  #7 (permalink)  
Old 05-19-2011, 05:54 AM
Vidar's Avatar
Junior Member
 
Join Date: May 2011
Location: Kempen, Germany
Posts: 31
Default

@Cynikal

No, these are modules, which include some kind of helper-functions. You can add them to your project with: "Project --> Add existing module" and use it, like Erel has described it in his example
  #8 (permalink)  
Old 05-19-2011, 06:54 AM
Kiffi's Avatar
Knows the basics
 
Join Date: Feb 2011
Location: Leverkusen, Germany
Posts: 238
Default

Hello Erel,

works like a charm. Thanks a lot!

Greetings ... Kiffi
__________________
Sorry for my weird english.
  #9 (permalink)  
Old 05-19-2011, 09:41 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,952
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

Quote:
I get an error with this:

java.lang.RuntimeException: Error loading Bitmap.

Debugger finds it in HttpUtilsService at

b = LoadBitmap(HttpUtilsService.TempFolder, SuccessfulUrls.Get(URL))
This can happen if the image file is corrupted or it is not an image file at all. It can also happen when you try to load a large bitmap and there is not enough memory.
  #10 (permalink)  
Old 05-22-2011, 08:46 AM
Junior Member
 
Join Date: May 2011
Posts: 87
Default

Getting an error when trying to use the 'GetString'

An error has occured in sub: httputils_issuccess (java line: 113)
java.lang.RuntimeException: Object should first be initialized (Map)
Closed Thread


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
DBUtils - Android databases are now simple! Erel Basic4android Getting started & Tutorials 108 04-21-2013 08:40 AM
Android SlidingPanels - Simple way to create sliding layouts Erel Basic4android Getting started & Tutorials 100 04-05-2013 08:29 PM
Anyone can help me design one simple Android Apps with Basic4android LouieChan Basic4android Updates and Questions 5 04-16-2012 12:32 AM
Email services and B4A NJDude Basic4android Updates and Questions 6 04-27-2011 03:33 AM
Help on SOAP Services sanoy Questions (Windows Mobile) 3 10-31-2008 06:39 AM


All times are GMT. The time now is 05:14 PM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0