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

ajk

Active Member
Licensed User
Longtime User
When I try to download page from http server on android with:
<p>ąśżźćńłó</p>
I get the:
<p>�������</p>
on WIN10 and android devices

how to handle this?
 

ajk

Active Member
Licensed User
Longtime User
Yes. Slightly modified by adding phrase mentioned above.
When I open the example file (in FILES folder) with browser it display correctly. The problem appear when I open the file served by http server from android phone.

OK SOLVED by adding:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
it was the utf-8 related issue
 
Last edited:

hatzisn

Expert
Licensed User
Longtime User
I tried using the http server by sending with POST a name value pair from vb.net with the following code:

(the sValue varible length is about 3850 characters)

B4X:
                    If sInfServ = "" Then
                sTempInfServ = InputBox("""Device address"" reported by http server:", "Insert IP", "")
                sTempInfServ = sTempInfServ.Replace(",", ".")
            Else
                sTempInfServ = sInfServ
            End If

            Dim nv As New NameValueCollection
            Dim sValue As String = Uri.EscapeDataString(sJson)

            nv.Add("json", sValue)

            Using webcl As New WebClient
                Try
                    Dim b() As Byte
                    b = webcl.UploadValues("http://" & sTempInfServ & ":5556/nvget/", nv)
                    MsgBox(System.Text.Encoding.UTF8.GetString(b))

                    sInfServ = sTempInfServ
                Catch ex As Exception
                    MsgBox("Internal error: " & ex.Message)
                    sInfServ = ""
                End Try
            End Using


The code in the 'http server' project is:

B4X:
Sub HandleNVGET (Request As ServletRequest, Response As ServletResponse)
    
    Try
    
        Dim sJson As String = DecodePath(Request.GetParameter("json"))
    
        Dim jp As JSONParser
        jp.Initialize(sJson)
        Dim l As List
        l.Initialize
        l = jp.NextArray
        .
        .
        .
        .
        .

    Catch
       Log(LastException)
       Response.SendString("Received the data but an error occured.")
    End Try

End Sub


When I compile the b4a project in debug mode everything works perfect. When I turn the compile mode in 'Release (obfuscated)' I get the error in the VB.NET app:
"The request was aborted: The request was canceled."

The error seen on the b4a side in logs is :"(NetworkOnMainThreadException) android.os.NetworkOnMainThreadException"

Any Ideas and suggestions on this?

Thanks
 
Last edited:

Roycefer

Well-Known Member
Licensed User
Longtime User
Is there any chance of this library being updated to more closely resemble B4J's jServer library? What would be really useful is if this library could run a WebSockets server like jServer. They're both based on jetty.
 

BluSky76

Member
Licensed User
Longtime User
I don't know how they externally send requests to my Android Server. Currently to solve the problem, temporarily, with Chrome you need to install an ALLOW-CORS plugin.
 

Ganiadi

Active Member
Licensed User
Longtime User
Hi Erel,

i Tried to install the server into mini pc device with android 9 Pie, it works, but when i click START SErver it raised error

upload_2019-12-12_13-38-34.png


upload_2019-12-12_13-39-42.png



Pls advice,
Tks
 
Status
Not open for further replies.
Top