Creating a local HTTP server on android
Some month back, I was trying to implement an app feature that allowed users to communicate(send texts and files) via a local HTTP connection, more like the way Xender works.
I searched for a lot of ways to do this, I found a few libraries but they didn’t offer the speed and simplicity I was looking for.
Eventually, after days of trying different libraries, I found Sun’s HttpServer.
This tutorial assumes you have basic knowledge of Kotlin and android development.
Let’s get started!!
The sun packages are not available on gradle so you’d have to include them in your project’s lib folder.
You can download the two jar files here . (Courtesy of @Oluwalekae)
Copy and paste the files as shown in this picture 👈
In your MainActivity.kt
- create a function to format our client’s inputStream to a string.
2. Declare a variable mHttpServer, data type HttpServer, which will be the instance of our server.
3. Create a method startServer, this is where we would start our server.
4. variable ‘rootHandler’ is an HttpHandler instance used to handle a request to the root path.
You can create as many handlers as you want based on the number of endpoints you want to have.
The mHttpServer.createContext() method allows us assign handlers to endpoints/routes.
We can add a messageHandler, in the end, our MainActivity.kt would look like this.
You can do most operations that you’d normally do on any http server, like Setting headers, handling file uploads, etc.
You can access the server from:
1. your browser from your phone’s browser using “http://127.0.0.1:5000”
2. or another device connected to your phone’s hotspot using “http://192.168.43.1:5000”
because is 5000 is our port number from the code.
Sun httpServer is the fastest server library you can get, trust me.
You can read more about the HttpServer here, and here.
Источник
Ioannis Diamantidis
A few days ago I wrote a post describing how to run an HTTP server from an iOS app. This intrigued me to start investigating how to implement a similar application on an Android app too. So, in this post I will describe how to setup and run an HTTP server from an Android app.
As I mentioned in the iOS post, such a setup (running a server from an app) can be utilized in many ways, with performing usability testing being one of those. If the app under test depends on a backend service, then we could apply some configuration to target the app with the server, which in turn would act as a mock server.
But enough with the intro, let’s move to the action.
Implementation
For the purposes of this app I am going to use Ktor framework to run the server. Ktor is a framework that helps implementing web-based applications and it can be used either on an Android app for the client-side logic or on a Kotlin server-side project. There is also support for Kotlin Multiplatform Projects which enables you to write the networking client code once in Kotlin and then compile to whatever platform you are interested in, for example iOS.
Sadly, Ktor Server is not currently supported but hopefully it will be sooner or later.
Dependencies
On a vanilla Android project, let’s add the dependencies on the app/build.gradle file:
We also have to add the following packagingOptions to avoid any build conflicts
The final app/build.gradle should look like the following:
Permissions
The next step is to add an entry on the AndroidManifest.xml regarding the INTERNET permissions like in the following snippet:
Finally, we can open our MainActivity.kt and add the following content:
We first create a server with Netty as the application engine, 8080 as the port and a module function. Inside this module function, we add the ContentNegotiation feature and register the gson converter. This will allow us to convert the request data to our model and our models to JSON responses. After that, we use the routing feature to define our endpoint and the response. The current implementation returns just a simple map, but it could also return a more complex data structure. Finally we start the server and we explicitly set to wait until we stop it.
We are now ready to run the app. After the app is successfully installed and running on either a device or a simulator, open the browser and hit localhost:8080 .
Voilà! You should get <"message": "Hello world">as a response!
Conclusion
To sum up, in this post we have seen how to run a simple HTTP server from an Android app using Ktor Server. In just 10 lines of code, we manage to create, set up and run an HTTP server. And with the JSON serialization installed.
Thanks for reading and should you have any questions, suggestions or comments, just let me know on Twitter or email me!!
Источник
Android-er
For Android development, from beginner to beginner.
Saturday, August 16, 2014
Implement simple HTTP server running on Android
Example to implement simple HTTP server on Android:
MainActivity.java
Updated@2015-11-25:
Permission of «android.permission.INTERNET» is needed in AndroidManifest.xml.
Updated@2015-11-26:
This code NOT work on Android 5, may be all 5+ version.
Fixed, refer post «socket.getInetAddress() return null on Android 5».
11 comments:
your blog is best.
how to share external storage directory and make them downloadable from pc. like wifi file sharing applications
Great Tutorial
Please sir/mam
how to share external storage directory and make them downloadable from pc. like wifi file sharing applications
I guess it will also require internet permission
How to send image through socket and user can download from it?
this application is not working as shown in the video. I added a few permissions to manifest file but still i don’t get logs on the screen. Can anyone help?
Dont socket.close() before reading InetAddress.
hello Mridul Gupta,
Yes, I already Updated@2015-11-26:
This code NOT work on Android 5, may be all 5+ version.
Fixed, refer post «socket.getInetAddress() return null on Android 5».
Just 2 small details:
1) don’t forget to add «:8888» after the IP on the URL you write in your browser
2) if you use the server from a browser on local network, eveything’s OK. But if you use it throught a Javascrit call, using XMLHttpRequest you’ll receive. nothing! In fact the server send a http.readyState at 4 (everything OK) but a http.status at 0 rather than 200. To get a http.status at 200 you must add a line in the header sended by the server. You must have:
os.print(«HTTP/1.1 200 OK» + «\r\n»);
os.print(«Access-Control-Allow-Origin: *» + «\r\n»);
Hope this will help.
@Andr.oid Eric. I think you have a config problem in your dev tool (Android Studio?). Because I use this small web server on a Samsung Galaxy TAB E running Android 4.4 and on a Samsung J2 running 6.01 and in both cases, it work like a charm. I tried it also on a really bad and old «low quality Chinese smartphone» and it works too.
Thank you very much..
It helped and exactly what i was looking for..
Can we use post instead of get to post additional data.
Thanks again.
used as sample. worked at first run,but not inside the emulator. only on real hardware.
Источник
How to create a HTTP server in Android? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago .
I would like to create a simple HTTP server in Android for serving some content to a client.
Any advice on how to build the server or use any existing library?
6 Answers 6
Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.
NanoHttpd works like a charm on Android — we have code in production, in users hands, that’s built on it.
The license absolutely allows commercial use of NanoHttpd, without any «viral» implications.
This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET is required.
The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket. If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.
If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.
Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.
Источник
Run http server on android
Android HTTP Server
Small but powerful multithreaded web server written completely in Java SE and then ported to Android.
The server implements most of the HTTP 1.1 specification and provides custom servlet API that can be used to handle dynamic pages. The servlet API is designed after the official javax.servlet API yet it is not compatible. Dynamic pages support cookies, sessions, file uploads and anything else to build a common web application.
- Small footprint, requires no external libraries
- Handles HTTP requests in separate threads
- Provides custom servlets API for generating dynamic content
- Supports GET, POST, HEAD methods (or more, depending on the configuration)
- Supports chunked transfer type
- Provides full support for mime types (uses Apache like mime.type)
- Supports buffered file upload (multipart requests), cookies, persisted sessions
- Supports serving partial body (ranges)
- Can serve static content both from file system and APK resources
Building the application
The provided Gradle wrapper should be used to build the application:
Installing Android SDK from command line
When running the full build for the first time you must first install the Android SDK. You might either install it manually or use the following script that downloads and installs all required dependencies to
To make things work after you logout and login back, configure the ANDROID_HOME environment variable:
The http subproject and the idea behind it
The http subproject is the heart of the application and it is independent on Android platform.
In fact the Android app was just an attempt to find a more practical use of the experimental HTTP protocol implementation.
One of the design goals was to keep the resulting artifact small in size and minimalistic in terms of dependency on other libraries — it does not require any third party component, all HTTP protocol implementation is based on parsing data read from raw TCP sockets.
Once the ro.polak.http package is mature enough it will be released as an independent artifact.
The subproject can be tested in the following way:
The original package code has been refactored and covered with unit and integration tests. Code coverage should be kept above 90%.
Android SDK compatibility issues
All application code is targeted to Java 7. It also compiles for the Android SDK versions finally block as an alternative when closing streams).
Another compatibility constraint is that Random instead of ThreadLocalRandom is used for generating random sequences in StringUtilities
Mutation tests can be run by executing the following command:
The results can then be found under http/build/reports/pitest/ro.polak.http/index.html and http/build/reports/pitest/ro.polak.http/mutation.xml .
Running standalone server (CLI)
Standalone server can be used to bundle the http subproject into a runnable server implementation. The CLI subproject is also independent on the Android platform, it is not bundled with the main APK.
It is also possible to build one «uber-jar» and to use it as a standalone application:
The resulting artifact can then be grabbed from ./cli/build/libs/cli-all.jar .
The standalone server jar can be run on any machine with the following command:
Overwriting configuration values from command line
For a complete list of available parameters refer to httpd.properties.
A demo application is automatically deployed to Heroku and can be reached at:
Please note the deployed application does not contain the admin application since that is only available for Android. See Procfile for the deployment description.
Hello World servlet
Request logging filter
Example servlets can be found in http/src/main/java/example.
A practical use of filters can be checked at SecurityFilter.java and LogoutFilter.java of the admin application.
Building a deployment descriptor
DeploymentDescriptorBuilder is an API alternative to traditional web.xml approach that aims to make servlet mapping building and filter registration easy. See example code below.
Serving static contents
Serving static resources is implemented using DefaultServlet
- the servlet is automatically registered as the very last element of DeploymentDescriptorBuilder acting as a fallback resource.
The actual resource loading is implemented by registering an instance ResourceProvider in the server config.
Currently there are two resource providers implemented
Sample dummy implementation of a ResourceProvider
The following example presents how to integrate Jtwig templating engine.
First you need to add Jtwig dependency in your gradle file:
Then it works out of the box:
500 error page trace in browser
Sample script to send SMS using wget command line utility
If you want to send a real SMS please remove «&test=1» from the POST params.
Android HTTP server uses icons from the beautifully designed «Farm-Fresh Web Icons» pack by FatCow Web Hosting! These icon sets are licensed under a Creative Commons Attribution 3.0 License.
The project is shared upon GNU GPLv3 license.
If you are interested in a dedicated commercial license please drop me a line at piotr [at] polak [dot] ro
About
A complete zero-dependency implementation of a web server and a servlet container in Java with a sample Android application.
Источник