在Android中实现一个简易的Http服务器

在Android中建立http服务器

最近遇到一个需求须要在App中建立一个Http服务器供供浏览器调用,用了下开源的微型Htpp服务器框架:NanoHttpd,项目地址:https://github.com/NanoHttpd/...java

直接上代码git

public class HttpServer extends NanoHTTPD {

    public HttpServer(int port) {
        super(port);
    }

    @Override
    public Response serve(IHTTPSession session) {

        HashMap<String, String> files = new HashMap<>();
        Method method = session.getMethod();

        if (Method.POST.equals(method)) {
            try {
                //notice:If the post with body data, it needs parses the body,or it can't get the body data;
                session.parseBody(files);
            }catch (IOException e) {
                return  newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT,
                        "SERVER INTERNAL ERROR: IOException: " + e.getMessage());
            }catch (ResponseException e) {
                return newFixedLengthResponse(e.getStatus(), MIME_PLAINTEXT, e.getMessage());
            }
        }

        final String postData = files.get("postData");

        String transJson = Transmit.getInstance().getAuthoriseData(postData);

        return newFixedLengthResponse(transJson);
    }

使用起来能够说是很简单了,session参数包含了请求的各类信息,这里显示获取了请求方法,由于咱们的项目中暂时只用post(demo),因此只针对post请求作了处理,get的处理会更简单。由于post请求中带有body,因此须要先声明一个HashMap,将body中的键值对取出来。这里咱们把请求过来的json数据映射到了"postData",而后从经过"github

final String postData = files.get("postData");

这行代码将其取出来.session还有getParams(),getCookies(),getHeaders()等方法,看名字就能够知道功能了。至此一个简单的Http服务器就出来了,一般把它放在一个service中等待请求。json

相关文章
相关标签/搜索