zoukankan      html  css  js  c++  java
  • 在Android中实现一个简易的Http服务器

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

    直接上代码

    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",然后从通过"

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

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

  • 相关阅读:
    ubuntu配置bridge网桥
    openstack 手动安装版 功能测试
    BC一周年B
    重构摘要11_处理概括关系
    深入浅出Redis(二)高级特性:事务
    补:小玩文件1-统计文本文件里的字符个数
    【C】字符串,字符和字节(C与指针第9章)
    怎样对报表的參数控件赋值
    POJ-2240 -Arbitrage(Bellman)
    ExtJS学习-----------Ext.Object,ExtJS对javascript中的Object的扩展
  • 原文地址:https://www.cnblogs.com/oneasdf/p/9244784.html
Copyright © 2011-2022 走看看