- Saved searches
- Use saved searches to filter your results more quickly
- License
- AndroThink/AndroidServer
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Running an HTTP server on an Android app
- Implementation
- Ktor
- Dependencies
- Permissions
- Code
- Conclusion
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Java android library for creating a Multi-Threaded Http Server on android .
License
AndroThink/AndroidServer
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Java android library for creating a Multi-Threaded Http Server on android .
- Dynamic routes .
- Support Http methods : GET ,POST ,PUT and DELETE .
- Handle body payload : plain text , json , formdata and xformurlencoded .
- Support response with : plain text , json , html and files .
allprojects < repositories < ... maven < url 'https://www.jitpack.io' > > >
Note that the minSdkVersion must be >= 16
dependencies < ... implementation 'com.github.AndroThink:AndroidServer:' >
These two routes response with the image or sound file that has the filename that exist in assets folder or response with 404 not found if not exist .
// Create routes .. ListRoute> routes = new ArrayList<>(); // Add not authorized route .. routes.add(new Route("/",ServerHelper.METHOD.GET, new RouteCallBack() < @Override public void onRequested(Request request, ResponseHandler responseHandler) < responseHandler.sendJsonResponse("\"status\":true,\"data\":\"Demo Response .\">"); > >)); // Add authorized route .. routes.add(new Route("/test",ServerHelper.METHOD.GET, true, new RouteCallBack() < @Override public void onRequested(Request request, ResponseHandler responseHandler) < String authKey = request.getApiKey(); responseHandler.sendJsonResponse("\"status\":true,\"data\":\"AthuKey " + authKey + ".\">"); > >)); // Response with html file .. // Add file to Assets folder then pass is path . routes.add(new Route("/html",ServerHelper.METHOD.GET, new RouteCallBack() < @Override public void onRequested(Request request, ResponseHandler responseHandler) < responseHandler.sendAssetFile(ServerHelper.RESPONSE_CODE.OK,ServerHelper.CONTENT_TYPE.HTML, "html/index.html"); > >)); // You can add placeholders inside your html and send its value within the response . // EX : simple html file called 500.html all text = error_place_holder inside the file // will be replaced with the text provided and so on .. routes.add(new Route("/htmlplaceholder",ServerHelper.METHOD.GET, new RouteCallBack() < @Override public void onRequested(Request request, ResponseHandler responseHandler) < MapString, String> placeHolders = new HashMap<>(); placeHolders.put("error_place_holder", "The text to be rendered"); responseHandler.sendAssetFileWithPlaceHolder(ServerHelper.RESPONSE_CODE.NOT_FOUND,ServerHelper.CONTENT_TYPE.HTML, "html/500.html", placeHolders); > >)); // and so on with sound => responseHandler.sendSoundResponse() // and so on with Images => responseHandler.sendImageResponse() // Create Server instance .. // You can pass ServerCallBack as ServerUtils.getInstance(routes,port,callBack) as server callback . ServerUtils serverUtils = ServerUtils.getInstance(routes,8080); // To Start Server if (serverUtils != null) serverUtils.start(Context); // To Stop Server if (serverUtils != null) serverUtils.stop();
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
If this project help you reduce time to develop, you can give me a cup of coffee 🙂
Copyright 2019 AndroThink . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
Java android library for creating a Multi-Threaded Http Server on android .
Running an HTTP server on an Android app
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
Ktor
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:
implementation "io.ktor:ktor:1.2.5" implementation "io.ktor:ktor-server-netty:1.2.5" implementation "io.ktor:ktor-gson:1.2.5"
We also have to add the following packagingOptions to avoid any build conflicts
packagingOptions exclude 'META-INF/*' >
The final app/build.gradle should look like the following:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android compileSdkVersion 28 defaultConfig applicationId "io.github.diamantidis.androidServer" minSdkVersion 28 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" > buildTypes release minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' > > packagingOptions exclude 'META-INF/*' > > dependencies implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.core:core-ktx:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation "io.ktor:ktor:1.2.5" implementation "io.ktor:ktor-server-netty:1.2.5" implementation "io.ktor:ktor-gson:1.2.5" >
Permissions
The next step is to add an entry on the AndroidManifest.xml regarding the INTERNET permissions like in the following snippet:
xmlns:android="http://schemas.android.com/apk/res/android" package="io.github.diamantidis.androidServer"> android:name="android.permission.INTERNET"/> android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> android:name=".MainActivity"> android:name="android.intent.action.MAIN" /> android:name="android.intent.category.LAUNCHER" />
Code
Finally, we can open our MainActivity.kt and add the following content:
package import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import io.ktor.application.call import io.ktor.application.install import io.ktor.features.ContentNegotiation import io.ktor.gson.gson import io.ktor.response.respond import io.ktor.routing.get import io.ktor.routing.routing import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty class MainActivity : AppCompatActivity() override fun onCreate(savedInstanceState: Bundle?) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) embeddedServer(Netty, 8080) install(ContentNegotiation) gson <> > routing get("/") call.respond(mapOf("message" to "Hello world")) > > >.start(wait = true) > >
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 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!!