Skip to content Skip to sidebar Skip to footer

How To Implement An Http Server On Android

I've two android applications on same LAN provided by WIFI : App (A) that open a listening socket on port 8033 App (B) that use HttpClient to access (A) on port 8033 How to make

Solution 1:

You may confuse two different level of networking communication. Level 4 : TCP connection between two sockets. A logical pipe between to side (may be single(two process?) or two different computers) only connection handling data are handle at this level Level 7 : Browser / Application Server used particular communication "language" to exchange high level data (file , images, audio ..) and is handled at this level. Your question is about to open a Listening Socket (level 4) and a client that talk with it with a HTTP protocol (level 7). So you're miss to fill the gap socket listening side to handle HTTP protocolMay be a java web server implementation may help you.

Solution 2:

Listening on a port and accepting socket connections isn't enough to serve data back to HttpClient. Sockets in effect provide a physical pipe but know nothing about the format of the data that's flowing along that pipe. If you are set on using HttpClient, then you'll need to have your server application understand HTTP protocol (or at least a very basic subset of it).

If all you need is to have two processes communicate in some way, you may be better off having your server app be a service and then your client app interrogate this service for the required data.

Solution 3:

I was looking for the same solution and found NanoHTTPD - an extremely simple HTTP request handling server class. You can find the source and very easy to understand samples at https://github.com/NanoHttpd

Solution 4:

Check out AndServer project available on github. Its a Web server and Web framework of Android platform. It provides annotations like SpringMVC.

@RestController@RequestMapping(path = "/user")
publicclassUserController {

    @PostMapping("/login")
    publicStringlogin(@RequestParam("account") String account,
                        @RequestParam("password") String password) {

        ...
        return"Successful.";
    }

    @GetMapping(path = "/{userId}")
    publicUserinfo(@PathVariable("userId") String userId,
                     @QueryParam("fields") String fields) {

        User user = findUserById(userId, fields);
        ...

        return user;
    }

    @PutMapping(path = "/{userId}")
    publicvoidmodify(@PathVariable("userId") String userId
                       @RequestParam("age") int age) {
        ...
    }
}

Simple deployment

Serverserver= AndServer.webServer(context)
    .port(8080)
    .timeout(10, TimeUnit.SECONDS)
    .build();

// startup the server.
server.startup();

...

// shutdown the server.
server.shutdown();

Post a Comment for "How To Implement An Http Server On Android"