Android Tutorial Embed an Http Server in your Android Application

Status
Not open for further replies.
The HttpServer library is a new library, based on an open source project named Jetty. This library allows you to easily embed an Http server in your application.

Http server means that you can point a browser to the device IP address (and relevant port) and communicate with your app.

It can be very useful in many applications.

Some of the benefits or reasons to use this library:
- No need to write any additional "client" app as the server can be accessed from any browser
- Much simpler to manage than raw sockets
- As the device plays the server role there are usually no firewall issues (when working in the local network)

The basics of this library are quite simple, though if you are not familiar with the Http protocol then it is recommended to first get familiarized with it.

How it works?
First you should initialize the server and call start with the chosen port. You should (usually) use a Service to handle the server.

Once the server is running, any external request will fire the HandleResponse event.

For example to create an interesting site that always returns a simple string you can write the following code:
B4X:
Sub Server_HandleRequest (Request As ServletRequest, Response As ServletResponse)
   Response.SendString("Hello")
End Sub

You can get more information from the Request object and then set the response accordingly.

The attached example demonstrates the features of this library.

Main page:

SS-2013-02-03_17.45.10.png


The code that builds this Html response, reads a template file and then replaces some of the fields as needed.
Note that the Greeting value is set in the main Activity.

The browser URL is made of the device local IP address and the chosen port.

This is the template text:

SS-2013-02-03_17.48.09.png


Pressing on the "List external storage files" link will take you to the "list" page:

SS-2013-02-03_17.50.25.png


The list page allows you to download or view the files, navigate to a different folder or to upload a file. Uploading a file is done with an "upload" call.

The server supports GET and POST requests. It will automatically handle multipart/form-data post requests (like is done with the uploading form).

The possibilities with this library are endless! You can pull reports from the device, export or import data, remotely control the device, handle multiple clients and many other options.

The library, which is quite large due to the Jetty library (1.5mb), can be downloaded here:
www.b4x.com/android/files/HttpServer.zip

The example is attached.

Other examples:
Multi-chat: http://www.b4x.com/forum/basic4android-getting-started-tutorials/25984-embed-http-server-your-android-application.html#post150462
Database reports: http://www.b4x.com/forum/basic4android-getting-started-tutorials/25984-embed-http-server-your-android-application-2.html#post150723

A module that allows you to use No-IP.org service and access devices over the internet: http://www.b4x.com/forum/basic4andr...ess-your-device-over-internet.html#post153944
 

Attachments

  • HttpServerExample.zip
    58.1 KB · Views: 7,514
Last edited:

pauleffect

Member
Licensed User
Longtime User
Dude... lan means sticking a lan cable in your device. like you do with your ROUTER. i don't think there's one phone/tablet out connected through a local area network (LAN).
wifi is what this lib does. you host a web page accessible through wifi.

web design and library? web design isn't a language dude. in order to do a page you need to design it. not within b4a. you write it in notepad or komodo or whatever strikes your fancy and that's it.
 
Last edited:

IslamQabel

Active Member
Licensed User
Longtime User
Dear Pauleffect.......I do not know how and why i said LAN? it was so stupid ......:(:mad::confused: Anyway, there was misunderstanding because i was thinking that we can access the web server in my mobile via Internet but i read one of comments that we have to do it with NO-IP.

i want to build web server on my mobile and access it via Internet for Home Automation issues.....Anyway If you have some comments that guide me....this will be OK

Thanks
 

pauleffect

Member
Licensed User
Longtime User
my advice, read a little about networking on wikipedia. Get acquainted with the related terms. Then decide what you want to do specifically.

I say this because it doesn't make sense doing home automation with an android device based server. A cheap laptop or an old pc, or a raspberry / arduino might prove more efficient for this kind of task. Even your home pc, provided you don't turn it off.
You write your server app in your language of choice: c++, c#, java, basic, whatever.
You assign it a port (google port forwarding) and you can access that port through 3g wherever you are.
Hosting a server on your phone is hardly the better choice. Hosting a server on your phone is hardly the smart choice (you know....security?).
But, if you are driven to do this, kindly follow Erel's advice and search for "no-ip".

Best of luck to you, friend.
 

IslamQabel

Active Member
Licensed User
Longtime User
Dear pauleffect :
You are right .....But Actually, i am working in Embedded Systems using micro-controllers and i actually made a complete system using micro-controllers and i know that web server in any PC as you said is the right choice but i would like to build small web server in my mobile for limited and small applications not for the whole Home Automation system of course.....
I know well that i can build web server using B4J which is simpler that using another languages in my opinion but till now i did not decide to learn extra language because i am programming micro-controllers using c compiler and recently using The amazing B4A to serve my embedded system and i am working alone.......design Hardware circuits+ Hardware Implementation+Micro-controllers programming+Android App design to control the system................My brain will explode...:D:eek::D if i learn extra programming.....What do you think? learn B4J or not..
Anyway thanks a lot for your Help
 

IslamQabel

Active Member
Licensed User
Longtime User
I made account @no-ip.org (free account).....There are many selections and i do not know what to select for Http server
1. Manage domains
2. Add domain
3. Add A Host
4. Manage Host ?

what is choice to make my mobile accessible from the internet?
 

pauleffect

Member
Licensed User
Longtime User
b4j and b4a are... well... almost the same. and easy as hell to grasp.

i know what wearing all the hats is and, as long as you take pleasure in your work, it's no problem.
anyway, if you encounter further problems in your endeavor, try starting a different thread.

have a good day!
 

IslamQabel

Active Member
Licensed User
Longtime User
I want to do something when i receive certain text from other users.....For example, when Desktop user send "HI" ......If the program in android receive "HI" from Desktop user ...it will do something.....So how to compare the received text???
 

GMan

Well-Known Member
Licensed User
Longtime User
Is it possible to make a DOWNLOAD from a listed file ?
 

pauleffect

Member
Licensed User
Longtime User
of course. it's exactly the same thing as accessing a web page hosted with xampp (on your pc) from your laptop. You can download anything you (or your client) sees.
 

kiki78

Active Member
Licensed User
Longtime User
Thank you Erel for this.

I try to use it in my application to serve recorded files.
This work, but I have small problem with ServletResponse.SendFile.
When I click on link, suggested filename in browser is complete path with underscore, as I expect only filename.
Example : Windows SaveDialog give me name "storage_sdcard0_MyPath_MyFile.ext", as I expect "MyFile.ext".
I try to split it and use 2 parameters of SendFile, but it's the same.
Have you solution ?

Regards
 

kiki78

Active Member
Licensed User
Longtime User
I reply myself.
Filename present to SaveDialog is part put after /download/ in Erel example.
So construct line with something like :
HTML:
"...<a href='/download/").Append(Filename).Append("'>Download</a>"
solve problem.
You just need to save path elsewhere.
 

tdocs2

Well-Known Member
Licensed User
Longtime User
Greetings, all.

I was able to run the example given and connect from a second tablet, downloaded and uploaded files.

From first post,
remotely control the device

What is the meaning of this and how is it done?

Thank you in advance for any help.

Sandy
 

mlc

Active Member
Licensed User
Longtime User
Hi all,
I added this type "video/mp4" to SetContentType, to see the videos in the browser.
B4X:
Sub SetContentType(FileName As String, Response As ServletResponse)
    Dim extension, ContentType As String
    Dim m As Matcher = Regex.Matcher("\.([^\.]*)$", FileName) 'find the file extension
    If m.Find Then
        extension = m.Group(1).ToLowerCase
        Select extension
            Case "html", "htm"
                ContentType = "text/html"
            Case "js"
                ContentType = "text/javascript"
            Case "gif", "png"
                ContentType = "image/" & extension
            Case "jpeg", "jpg"
                ContentType = "image/jpeg"
            Case "css", "xml"
                ContentType = "text/" & extension
            Case "ico"
                ContentType = "image/vnd.microsoft.icon"
            Case "txt"
                ContentType = "text/plain"
            Case "mp4"
                ContentType = "video/mp4"
            Case Else
                ContentType = "application/octet-stream"
        End Select
        Response.SetContentType(ContentType)
    End If

No problem to watch videos less than 2MB, which exceed 2MB I get this error:
B4X:
/download/mnt%2Fsdcard%2FWhatsApp%2FMedia%2FWhatsApp+Video%2FVID-20130502-WA0003.mp4
2014-11-26 11:14:41.846:WARN::/download/mnt%2Fsdcard%2FWhatsApp%2FMedia%2FWhatsApp+Video%2FVID-20130502-WA0003.mp4
java.lang.RuntimeException: org.eclipse.jetty.io.EofException
    at anywheresoftware.b4a.objects.Servlet.handleRequest(Servlet.java:105)
    at anywheresoftware.b4a.objects.Servlet.doGet(Servlet.java:73)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:538)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:478)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:937)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:406)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:871)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:346)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:589)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1048)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:601)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:214)
    at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:411)
    at org.eclipse.jetty.server.nio.BlockingChannelConnector$BlockingChannelEndPoint.run(BlockingChannelConnector.java:289)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$1.run(QueuedThreadPool.java:529)
    at java.lang.Thread.run(Thread.java:1019)
Caused by:
org.eclipse.jetty.io.EofException
    at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:911)
    at org.eclipse.jetty.http.AbstractGenerator.flush(AbstractGenerator.java:433)
    at org.eclipse.jetty.server.HttpOutput.flush(HttpOutput.java:89)
    at org.eclipse.jetty.server.HttpConnection$Output.flush(HttpConnection.java:1139)
    at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:172)
    at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:96)
    at anywheresoftware.b4a.objects.streams.File.Copy2(File.java:357)
    at anywheresoftware.b4a.objects.Servlet.handleRequest(Servlet.java:100)
    at anywheresoftware.b4a.objects.Servlet.doGet(Servlet.java:73)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:538)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:478)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:937)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:406)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:871)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:346)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:589)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1048)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:601)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:214)
    at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:411)
    at org.eclipse.jetty.server.nio.BlockingChannelConnector$BlockingChannelEndPoint.run(BlockingChannelConnector.java:289)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$1.run(QueuedThreadPool.java:529)
    at java.lang.Thread.run(Thread.java:1019)
Caused by:
java.net.SocketException: Connection reset by peer
    at org.apache.harmony.luni.platform.OSNetworkSystem.write(Native Method)
    at dalvik.system.BlockGuard$WrappedNetworkSystem.write(BlockGuard.java:284)
    at org.apache.harmony.nio.internal.
Message longer than Log limit (4000). Message was truncated.

However, no problem to download it

Any ideas?

thank you
 
Status
Not open for further replies.
Top