Hello everyone, today I would like to introduce to you an open source project that allows native Android to do Web development — AndServer.

Open source: github.com/yanzhenjie/…

AndServer is an Android Web server, similar to Apache or Tomcat, but different, it is a common Android Library, Android projects Gradle remote dependencies or add Jar packages into the project. Then you develop your App as normal Android development.

AndServer uses pure Android APIS to write a library, so it doesn’t need any third-party libraries or hardware to compile it, and only 580KB after packing it into jars.

A lot of people look at this and wonder: What are the usage scenarios? According to international practice, LET me give you an example:

A company has unveiled a TV APP that can be installed on a TV or a box and has one function like this: On the APP is installed on the TV, generates a unique ID, the user by companies to provide the public with WeChat sweep code number and the bound the APP on the TV, the user through public open a H5 page, the page you can upload pictures or video to the server, the server detects the user and a screen of the APP binding, Dynamically send pictures or videos sent by the user to the TV for playback. Such a feature is a good experience, but it takes server resources, remote upload, and remote download time, so I’d rather just copy it to the TV with a USB flash drive. Wouldn’t it be more direct and fast if I directly send the video or picture to the APP on THE TV through the LAN through the web?

Of course, most students may be less exposed to the needs of APP communication on LAN, LAN upload and download, LAN login and so on. There are many other things I will not mention, let’s start the formal Amway.


The characteristics of

  1. Accept client file upload and download.
  2. Dynamic Http APIS that write interfaces like Java servlets.
  3. Deploy static web sites, such as pure Html, support JS, CSS, Image separation.
  4. Deploying dynamic web sites, such as Html forms, can of course be combined with the Android Http interface above.

Basically the same functionality as Java servlets should be familiar if you’ve done Java development or Web development in other languages.

Rely on

  • Gradle

    compile 'com. Yanzhenjie: andserver: 1.0.2'Copy the code
  • Maven

    <dependency>
    <groupId>com.yanzhenjie</groupId>
    <artifactId>andserver</artifactId>
    <version>1.0.2</version>
    <type>pom</type>
    </dependency>Copy the code
  • ADT, you can download the Jar package from the AndServer home page.

Method of use

The best tutorial is Sample. It is recommended to go to the AndServer home page to download the sample and run it to see what it looks like.

Creating a Server

AndServer andServer = new AndServer.Build()
    ...
    .build();

// Create a server.Server mServer = andServer.createServer(); .// Start the server.mServer.start(); .// Stop the server.mServer.stop(); .// Is the server running?
boolean running = mServer.isRunning();Copy the code

Port number and response timeout Settings

AndServer andServer = new AndServer.Build()
    .port(8080) // The default port number is 8080.
    .timeout(10 * 1000) // Default 10 * 1000 ms.. .build(); .Copy the code

Deploy the site

You can also implement this interface yourself. Of course, AndServer already provides two default implementations:

  • AssetsWebsite
  • StorageWebsite

If you register your site with the above two implementations, your default home page (index.html) will be:

http://ip:port/
http://ip:port/youPath
http://ip:port/youPath/index.htmlCopy the code

Register the site to AndServer

Wesite wesite = new AssetsWebsite(AssetManager, youPath);
/ / or
Wesite wesite = new StorageWebsite(youPath);

AndServer andServer = new AndServer.Build()
    ...
    .website(wesite);
    .build();Copy the code

The use of AssetsWebsite

If your site is under Assets, then you deploy your site using AssetsWebsite.

The method of use is:

//AssetManager cannot be closed.
AssetManager mAssetManager = getAssets();

Wesite wesite = new AssetsWebsite(mAssetManager, youPath);Copy the code

As we saw above, we need to pass an AssetManager and a path to the new AssetsWebsite. Path supports the root and subdirectories of assets. The following are examples of these two situations.

  • If your website is inassetsIn the root directory, yourspathJust fill out"", such as:
The root directory of Assets

Wesite wesite = new AssetsWebsite(mAssetManager, "");Copy the code

Your default home page address is:

http://ip:port
http://ip:port/index.htmlCopy the code

Then your other page access address is:

http://ip:port/login.html
http://ip:port/error.htmlCopy the code

Such as:

http:/ / 192.168.1.12:8080 / index. HTML
http:/ / 192.168.1.12:8080 / login. HTMLCopy the code
  • If your site root directory is inassetsSubdirectory, then you pass inassetsThe relative directory address of your website is goodassetsUnder thewebContents, for example:
Assets subdirectories

Wesite wesite = new AssetsWebsite(mAssetManager, "web");Copy the code

Your default home page address is:

http://ip:port
http://ip:port/web
http://ip:port/web/index.htmlCopy the code

Then your other page access address is:

http://ip:port/web/login.html 
http://ip:port/web/error.htmlCopy the code

Such as:

http:/ / 192.168.1.12:8080 /
http:/ / 192.168.1.12:8080 / index. HTML
http:/ / 192.168.1.12:8080 / web/index. The HTML
http:/ / 192.168.1.12:8080 / web/index. The HTML
http:/ / 192.168.1.12:8080 / web/login. HTMLCopy the code

The use of StorageWebsite

If your site is in memory, as long as it is accessible as a file, then you can use StorageWebsite to deploy your site, such as when your site is on an SD card.

The method of use is:

Wesite wesite = new StorageWebsite(youPath);Copy the code

It is as simple as passing in the address of your website’s storage directory, such as your website’s WWW directory under the SD card:

File file = new File(Environment.getExternalStorageDirectory(), "www");
String websiteDirectory = file.getAbsolutePath();

Wesite wesite = new StorageWebsite(websiteDirectory);Copy the code

The access address is the same as AssetsWebsite.

Write the Http interface like a Servlet

The Http API is registered through the RequestHandler interface, which is a Java interface, just like a Java Servlet.

You need to implement this interface and register with AndServer, for example:

public class RequestLoginHandler implements RequestHandler {

    @Override
    public void handle(HttpRequest req, HttpResponse res, HttpContext con) {
        Map<String, String> params = HttpRequestParser.parse(request);

        // Request params.        
        String userName = params.get("username");
        String password = params.get("password");

        if ("123".equals(userName) && "123".equals(password)) {
            StringEntity stringEntity = new StringEntity("Login Succeed"."utf-8");
            response.setEntity(stringEntity);
        } else {
            StringEntity stringEntity = new StringEntity("Login Failed"."utf-8"); response.setEntity(stringEntity); }}}Copy the code

Then register with AndServer:

AndServer andServer = new AndServer.Build()
    ...
    .registerHandler("login".new RequestLoginHandler())
    .build();Copy the code

You now have a unique access address: http://ip:port/login, for example:

http:/ / 192.168.1.12:8080 / login? username=123&password=123Copy the code

For examples of file download and file upload, download sample.

Submit the Html form to the Android end

In the Html form action, fill in the key you registered with the RequestHandler, and in the RequestHandler

handle(HttpRequest, HttpResponse, HttpContext)Copy the code

Method to retrieve the parameters submitted by the form.

For example, we registered Login RequestHandler above and used it like this in the form:

<form id="form1" method="post" action="login">.</form>Copy the code

Listen for the status of the server

Generally, the server has three states: successfully started, failed to start, and successfully stopped. When the server fails, an exception is returned. In most cases, the network is faulty or the port is occupied.

private Server.Listener mListener = new Server.Listener() {
    @Override
    public void onStarted(a) {
        // The server started successfully.
    }

    @Override
    public void onStopped(a) {
        // The server stops, usually when the developer calls server.stop().
    }

    @Override
    public void onError(Exception e) {
        // An error occurred during server startup.}}; AndServer andServer =new AndServer.Build()
    ...
    .listener(mListener)
    .build();Copy the code

If you like it, please follow my wechat official account

YanZhenJie