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:

mlc

Active Member
Licensed User
Longtime User
Hello,

It's possible to upload files with Ajax?

Thanks
 

IslamQabel

Active Member
Licensed User
Longtime User
Hi Erel:

No it did not work as i want so i am asking you, However i tried this code and i want to know what is the wrong with it:
B4X:
Sub Server_HandleRequest (Request As ServletRequest, Response As ServletResponse)
    Try
        Log("Client: " & Request.RemoteAddress)
        Log(Request.RequestURI)
        Select True
            Case Request.RequestURI = "/"
                HandleMainPage (Response)
            Case Request.RequestURI.StartsWith("/Page2/")
              HandlePage20(Response)
    End Select
    Catch
        Response.Status = 500
    End Try

End Sub

then i added a new sub-routines to handle "Page2.html" which is saved in Files folder of my project:
B4X:
Sub HandlePage20(Response As ServletResponse)
      Dim Page20 As String=GetTemplate("Page2.html")
     '******displaying the time in the second page***
     Page20=Page20.Replace("$T$",DateTime.Time(DateTime.Now))
Response.SetContentType("text/html")
Response.SendString(Page20)
End Sub

although the compiler did not display any error message, when i type in web browser 192.168.1.100:5555/Page2 or /Page2/ or /Page2.html i saw blank page

thanks
 
Last edited:

IslamQabel

Active Member
Licensed User
Longtime User
how to add login filter to the main page? username & password are displayed when i access to the server ?
 

mlc

Active Member
Licensed User
Longtime User
It's possible to upload files with Ajax?

The server expects files encoded in the multipart protocol. I don't think that it will work with ajax uploads.

Hello,
With this code, I can upload multiple files to the server.

B4X:
<!DOCTYPE html>
<html>
<head>
    <title>XHR1</title>
    <script>

    var xhr = new XMLHttpRequest();

    function send(){

      var fd= new FormData(document.forms.namedItem("fileinfo"));
      xhr.open("POST", "/uploadf/", true);
      xhr.send(fd);
    }

    xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.statusText);
                    }
              }

    </script>
</head>

<body>
<form enctype="multipart/form-data" method="post" name="fileinfo" action="/uploadf/">
  <input type="file" id="file-select" name="file" required/ multiple>
  <input type="submit" value="Send Files" onclick="send" />
</form>

</body>
</html>

In the image below, you can view the files in the temporary folder and the file names in the request (the value is an array).
Key = "file"

upload_2015-2-2_18-27-40.png


But the problem is that Request.GetUploadedFile("file") expects a string.

B4X:
Sub HandleUploadf(Request As ServletRequest, response As ServletResponse)
    Dim upload As String = Request.GetUploadedFile("file")
    'copy the temporary file to the correct folder
    File.Copy(server.TempFolder, upload, Main.Recibidos, Request.GetParameter("file")) 'the file name is sent as a parameter
    File.Delete(server.TempFolder, upload) 'delete the temporary file.
    response.SendString("OK")
End Sub

and do not know how to extract individual files.

Any ideas? It is possible?

Note: The code works fine for a single file.

thanks
 
Last edited:

acbarbosa

New Member
Licensed User
Longtime User
Hello Erel,

Is it possible to use this HTTP server with a HTTPClient using WebView or WebViewExtras, or something similar inside the same B4A app?
 

IslamQabel

Active Member
Licensed User
Longtime User
Erel said:
You can return any html you like. You will need to return a html page with form and then handle the form request with the user name and password.

Note that B4J http server solution is much more powerful and also simpler.

The required issue is http server on the mobile...
 

IslamQabel

Active Member
Licensed User
Longtime User
In the subroutine of HandleMainPage.....
MainPage = MainPage.Replace("$T$", DateTime.time(DateTime.Now))

This will only show the time when the page loaded only...but if i want to show the updated value of the my mobile time what to do??? without refreshing the web page
 
Last edited:

IslamQabel

Active Member
Licensed User
Longtime User
So.....as i understood...should i add some codes to my HTML page that request periodically the server ? or should i add some modifications in the android app?
 

mlc

Active Member
Licensed User
Longtime User

IslamQabel

Active Member
Licensed User
Longtime User
Hello MLC:

thanks for your help.....Actually, i tried using your links before but it does not work with my app variables....so instead of using them, i used the AJAX request and it works.....
Thanks a lot
 
  • Like
Reactions: mlc

androidtom

Member
Licensed User
Longtime User
I must have something not configured correctly since others seem to be able to compile this example without problems. I have tried various versions of Java from 1.7 to 1.8. Currently my javac is at 1.7.0_79 and I have configured the path in the IDE to point to it. The error I get when compiling the httpserver example is the following:

Compiling generated Java code. Error
javac 1.7.0_79
src\b4a\example\serverservice.java:88: error: cannot find symbol
public static anywheresoftware.b4a.objects.HttpServer _server = null;
^
symbol: class HttpServer
location: package anywheresoftware.b4a.objects
Note: src\b4a\example\serverservice.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

>>>> Problem solved. I re-installed B4a ver 4.3 along with the appropriate libraries. It compiles now. (Not sure what fixed it, but it now works)

What am I missing?
Thank you!!!
 
Last edited:

IslamQabel

Active Member
Licensed User
Longtime User
Hi All...
Does anyone know how to link directly to an image saved in the phone memory or memory card....for example..in the camera example the image was saved with fixed name ...everytime you capture an image it will be saved as follows:
/mnt/sdcard/1.jpg.....when i browse my server i want to put hyperlink that display the image directly when i click it without displaying the other images or contents of my phone how to do that?
 

Ekcentrik

Member
Licensed User
Longtime User
Hi,
I would like to know if it's possible to use HTTPS instead of plain HTTP with this library.
If so , anyone can send me a small example code please?
I would like to send encrypted request on a server(mobile phone).
Thank you for your help.
Marcel
 
Status
Not open for further replies.
Top