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,309
Last edited:

bernd33

New Member
Licensed User
Longtime User
Thanks for the quick answer.

The Chatexample is a automatic reload of the whole page every 5 Seconds? Sorry, but that is what I will prevent and the reason why I ask for Websockets.

Maybe I'm wrong but I think with Websockets it's possible to establish a bidirectional Server/Client realtimecommunication. So a "server part/program" can send new Values/Events/Whatever to the client and the Client will update only a part of the Webpage without reload the whole page.

In this case Server means Webserver Jetty and client mens Browser/IE/Crome/Safari.

But as I said. I'm new to this stuff and maybe I'm complete wrong :eek:


Regards, Bernd
 

bernd33

New Member
Licensed User
Longtime User
Hi,

two more little question :) Where is the httpdoc-rootpath? Is security like password/session implemented?

1.) Other Webservers like apache or iis have a rootpath for the html-documents. Where can I find this path?
I played arround with the httpserver and I was able to add a picture wich is stored on my Sdcard onto a Webside.
Also in the example I can list all directorys and files from my devices. This makes me a bit nervouse because when the Webserver is running and somebody visits the webside, this person is able to access all files/folders from the device?
1.1) Is the whole device the httpdoc-rootpath? If yes, is it possible to define a httpdoc-rootpath wich is the only accessable path from web side?

2.) Is any security function build in? Something like password/session?

The reason why I ask: With B4A and the httpserver I have a perfect combination to access/control my Atmega microcontrollers. No more needs to write a client program :sign0060: The androiddevice controlls/talks/querys by wlan the Atmega and a Webside shows me all I want on any device from anywhere on the world :icon_clap:

But... If the Webserver is accessable from the Internet, there should be a bit of security :)

Thanks a lot and regards, Bernd
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
1) You should use Request.SendFile to server static files. They aren't served automatically. This means that it is up to you to decide which files will be served and how.

2) Note that your device will not be accessible from the internet. Unless you configure it as explained here: No-IP Android client - Access your device over the internet

You can easily implement a simple password / username check.
 

jgbozza

Member
Licensed User
Longtime User
When using the httpserver, the first remote request takes too long to fire the HandleRequest event. Once it's fired, the next requests go quickly.

If I don't send any request for a certain time, when I do it again it takes the same amount of time to fire the event as if I was doing it for the first time

Is that any issue with my WiFi networ? Is there any parameter that I can set in the software to avoid this response delay ?:sign0148:

I measured the time and it is always 30 seconds prior to fire the event!
 
Last edited:

jiangws

Member
Licensed User
Longtime User
Could I use css at template.html?

It's great chat program!

But it's diffucult to input characters at mobile phone. Could I use css at template.html? I want to put at apk, where to put and how to use it?

Thanks.
 

luke2012

Well-Known Member
Licensed User
Longtime User
Very very interesting library.

This library is in my app enanchements planning but I suppose that my B4A ver. 1.93 isn't compatible. Right?
 

luke2012

Well-Known Member
Licensed User
Longtime User
The query is executed in Server_HandleRequest:
B4X:
table = DBUtils.ExecuteHtml(SQL, query, Null, 200, False)
You should change this code to use SQL.ExecNonQuery.

You mean to replace the entire statement with the SQL.ExecNonQuery statement ?
 

Mahares

Expert
Licensed User
Longtime User
How to Upload and Download Files From a HTTP Embedded server

I configured a Galaxy 7 inch tablet as a HTTP Server using Erel’s HTTP lib. I would like each of 4 other phones/tablets devices to upload to it text files or download from it text files. I tried the below code, but it is obviously incorrect. When I tried to connect to it from another device, it displayed the content of the text file located on the server (7 in Galaxy) DirRootExternal on the screen.

B4X:
Sub Server_HandleRequest (Request As ServletRequest, Response As ServletResponse)
   Response.SendFile(File.DirRootExternal,"daily.txt")
End Sub
What is the piece of code I need in the serverService module to upload to it or and download from it files.
Thank you for any tips, code, etc. that can bring a smile to a needy poor fellow.
 

metrick

Active Member
Licensed User
Longtime User
I got "Application not installed" on my Samsung Galaxy S Android version 2.3.3.
 

metrick

Active Member
Licensed User
Longtime User
Problem is solved with uninstall an app with the same name. Now the app forced closed when open.
Here is a paste from output logs.
** Activity (main) Create, isFirst = true **
Ip address: 192.168.1.103
** Activity (main) Resume **
** Service (serverservice) Create **
2013-07-28 06:46:23.795:INFO::jetty-7.x.y-SNAPSHOT
2013-07-28 06:46:23.883:INFO::started o.e.j.s.ServletContextHandler{/,null}
2013-07-28 06:46:23.889:WARN::FAILED [email protected]:7777 FAILED: java.net.BindException: Address already in use
2013-07-28 06:46:23.890:WARN::FAILED org.eclipse.jetty.server.Server@4057cce8: java.net.BindException: Address already in use
serverservice_service_create (java line: 177)
 

alienhunter

Active Member
Licensed User
Longtime User
Thanks Erel

works like a charm

I modified a bit your code and I can have 2 Tables or more ...

AH
 

Attachments

  • html1.jpg
    html1.jpg
    201.2 KB · Views: 520
Status
Not open for further replies.
Top