AndServer Documentation

repository·master·Indexed 26 days ago

https://github.com/yanzhenjie/andserver

An HTTP and reverse proxy server designed for the Android platform. It provides a web server and web framework using SpringMVC-style annotations for static website deployment and dynamic API development. Key features include support for @RestController and @RequestMapping, custom error handling via ExceptionResolver, and a ProxyBuilder for mapping hostnames to backend URLs.

Tokens
2K
Snippets
5
Records
11
Agent score
87%

What's inside AndServer

  1. Install AndServer in a Gradle project

    master

    To use AndServer, you must first add the AndServer plugin to your buildscript and then apply the plugin and dependencies to your module.

    If you are using Kotlin, use kapt instead of annotationProcessor for the processor dependency.

    // 1. Add plugin to buildscript
    buildscript {
        repositories {
            google()
            mavenCentral()
        }
    
        dependencies {
            classpath 'com.yanzhenjie.andserver:plugin:2.1.12'
        }
    }
    
    allprojects {
        repositories {
            google()
            mavenCentral()
        }
    }
    
    // 2. Apply plugin and add dependencies to your module
    apply plugin: 'com.yanzhenjie.andserver'
    
    dependencies {
        implementation 'com.yanzhenjie.andserver:api:2.1.12'
        annotationProcessor 'com.yanzhenjie.andserver:processor:2.1.12'
    }
  2. Deploy an AndServer Web Server

    master

    You can deploy a web server for static HTML or dynamic HTTP API deployment using the AndServer.webServer(context) builder. You can configure the port, timeout, and other settings like inetAddress, serverSocketFactory, or sslContext.

    Server server = AndServer.webServer(context)
        .port(8080)
        .timeout(10, TimeUnit.SECONDS)
        .build();
    
    // startup the server.
    server.startup();
    
    // ...
    
    // shutdown the server.
    server.shutdown();
  3. Deploy an AndServer Reverse Proxy Server

    master

    You can deploy a reverse proxy server using AndServer.proxyServer(). Use .addProxy(host, targetUrl) to map specific hostnames or IP addresses to target backend URLs.

    Note: This is a pure reverse proxy and does not include load balancing capabilities.

    Server server = AndServer.proxyServer()
        .addProxy("www.example1.com", "http://192.167.1.11:8080")
        .addProxy("example2.com", "https://192.167.1.12:9090")
        .addProxy("55.66.11.11", "http://www.google.com")
        .addProxy("192.168.1.11", "https://github.com:6666")
        .port(80)
        .timeout(10, TimeUnit.SECONDS)
        .build();
    
    // startup the server.
    server.startup();
    
    // ...
    
    // shutdown the server.
    server.shutdown();
  4. Define HTTP APIs using SpringMVC-style annotations

    master

    AndServer uses annotations similar to SpringMVC to define RESTful APIs. You can use @RestController and @RequestMapping for class-level routing, and @GetMapping, @PostMapping, and @PutMapping for method-level routing. Path variables can be captured using @PathVariable, and query parameters using @RequestParam or @QueryParam.

    @RestController
    @RequestMapping(path = "/user")
    public class UserController {
    
        @PostMapping("/login")
        public String login(@RequestParam("account") String account, 
                            @RequestParam("password") String password) {
            return "Successful.";
        }
    
        @GetMapping(path = "/{userId}")
        public User info(@PathVariable("userId") String userId, 
                         @QueryParam("fields") String fields) {
            User user = findUserById(userId, fields);
            return user;
        }
    
        @PutMapping(path = "/{userId}")
        public void modify(@PathVariable("userId") String userId, 
                           @RequestParam("age") int age) {
            // ...
        }
    }
  5. Access connection information via HttpRequest

    master

    Within an API method, you can use the HttpRequest object to retrieve connection details for both the local server and the remote client.

    @GetMapping(path = "/connection")
    void getConnection(HttpRequest request, ...) {
        request.getLocalAddr();   // HostAddress
        request.getLocalName();   // HostName
        request.getLocalPort();   // server's port
    
        request.getRemoteAddr();  // HostAddress
        request.getRemoteHost();  // Especially HostName, second HostAddress
        request.getRemotePort();  // client's port
    }
  6. Configure a standard Server using Builder

    master

    Use the Builder interface to configure a standard web server instance before calling build(). Available configuration options include:

    • inetAddress(InetAddress): Specify the IP address to monitor.
    • port(int): Specify the port number for the server to listen on.
    • timeout(int, TimeUnit): Set the connection and response timeout.
    • serverSocketFactory(ServerSocketFactory): Assign a custom ServerSocketFactory.
    • sslContext(SSLContext): Assign an SSLContext for HTTPS support.
    • sslSocketInitializer(SSLSocketInitializer): Assign an SSLSocketInitializer.
    • listener(Server.ServerListener): Set a listener to handle lifecycle events.
  7. Implement ExceptionResolver to handle custom errors

    master

    Implement the ExceptionResolver interface to intercept exceptions occurring during request processing. This allows you to customize the HTTP response (status code and body) when an error occurs.

    By default, AndServer uses a DEFAULT resolver that sets the status code to the one provided by HttpException (or 500 Internal Server Error if it's a generic exception) and sets the response body to the exception's message.

    To wrap an existing resolver with additional logic (for example, to automatically handle MethodNotSupportException by adding the Allow header), use the ResolverWrapper class.