`
fly_hyp
  • 浏览: 302249 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

lightweight HTTP server 从HttpExchange 解析参数

    博客分类:
  • Java
阅读更多

 

转自:http://leonardom.wordpress.com/2009/08/06/getting-parameters-from-httpexchange/

 

You now in Java 6 has some APIs to create lightweight HTTP server. Well, today, I had to created a lightweight HTTP server embedded in an application, but when I try to get the parameters for a request I noticed the HttpExchange class doesn’t have a method for that.

After some researches on Google, I come across a solution.

What I did was to create a Filter class which will deal with the parameters parse:

public class ParameterFilter extends Filter {

    @Override
    public String description() {
        return "Parses the requested URI for parameters";
    }

    @Override
    public void doFilter(HttpExchange exchange, Chain chain)
        throws IOException {
        parseGetParameters(exchange);
        parsePostParameters(exchange);
        chain.doFilter(exchange);
    }    

    private void parseGetParameters(HttpExchange exchange)
        throws UnsupportedEncodingException {

        Map<String, Object> parameters = new HashMap<String, Object>();
        URI requestedUri = exchange.getRequestURI();
        String query = requestedUri.getRawQuery();
        parseQuery(query, parameters);
        exchange.setAttribute("parameters", parameters);
    }

    private void parsePostParameters(HttpExchange exchange)
        throws IOException {

        if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
            @SuppressWarnings("unchecked")
            Map<String, Object> parameters =
                (Map<String, Object>)exchange.getAttribute("parameters");
            InputStreamReader isr =
                new InputStreamReader(exchange.getRequestBody(),"utf-8");
            BufferedReader br = new BufferedReader(isr);
            String query = br.readLine();
            parseQuery(query, parameters);
        }
    }

     @SuppressWarnings("unchecked")
     private void parseQuery(String query, Map<String, Object> parameters)
         throws UnsupportedEncodingException {

         if (query != null) {
             String pairs[] = query.split("[&]");

             for (String pair : pairs) {
                 String param[] = pair.split("[=]");

                 String key = null;
                 String value = null;
                 if (param.length > 0) {
                     key = URLDecoder.decode(param[0],
                         System.getProperty("file.encoding"));
                 }

                 if (param.length > 1) {
                     value = URLDecoder.decode(param[1],
                         System.getProperty("file.encoding"));
                 }

                 if (parameters.containsKey(key)) {
                     Object obj = parameters.get(key);
                     if(obj instanceof List<?>) {
                         List<String> values = (List<String>)obj;
                         values.add(value);
                     } else if(obj instanceof String) {
                         List<String> values = new ArrayList<String>();
                         values.add((String)obj);
                         values.add(value);
                         parameters.put(key, values);
                     }
                 } else {
                     parameters.put(key, value);
                 }
             }
         }
    }
}

After that you can add this filter to your HttpServer context:

HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
HttpContext context = server.createContext("/myapp", new myHttpHandler());
context.getFilters().add(new ParameterFilter());
server.start();

Then you can do something like below in your HttpHandler to get the parameters:

public class MyHttpHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        Map<String, Object> params =
           (Map<String, Object>)exchange.getAttribute("parameters");

        //now you can use the params
    }
}

Well, that’s all! I hope you enjoy the tip!

分享到:
评论

相关推荐

    基于stm32f407+lwip 的web server设备参数配置.rar

    如果是POST方法,可能涉及到设备参数的提交,此时服务器会解析POST数据,更新设备参数,并返回确认信息。 4. **设备参数配置**:设备参数通常存储在MCU的Flash或EEPROM中,通过HTTP POST请求可以将新的配置参数传递...

    Nginx HTTP Server, Third Edition,英文

    Nginx is a lightweight HTTP server designed for high-traffic websites, with network scalability as the primary objective. With the advent of high speed Internet access, short loading times and fast ...

    WebSocket Lightweight Client-Server Communications pdf mobi epub 格式 及源代码

    直到最近,在浏览器中创建类似桌面的应用程序意味着使用低效的Ajax或Comet技术与之通信服务器。 通过本实用指南,您将学习如何使用WebSocket, 使客户端和服务器能够与每个通信的协议其他同时在一个连接上。...

    IBM http server 启用SSL

    在IBM HTTP Server和WebSphere环境中,SSO通常通过插件和LTPA(Lightweight Third-party Authentication)令牌实现。在项目中,你需要配置Web应用程序信任LTPA令牌,这样当用户通过SSL连接登录到一个应用后,他们...

    Nginx HTTP Server, 4th Edition-Packt Publishing(2018).epub

    However, for the past few years, the same reports reveal the rise of a new competitor: Nginx, a lightweight HTTP server originating from Russia—pronounced engine X. There have been many questions ...

    lightweight清爽简洁的编辑器

    《lightweight清爽简洁的编辑器探索》 在数字化时代,编辑器成为了我们日常工作中不可或缺的工具,特别是对于程序员、作家以及任何需要处理文本的人来说。"lightweight清爽简洁的编辑器"这一主题,恰恰迎合了现代...

    A_flexible_and_lightweight_web_server_fiery.zip

    A_flexible_and_lightweight_web_server_fiery

    基于Stm32的嵌入式WebServer例程

    3. **HTTP服务器框架**:这是一段用于解析HTTP请求、构建响应和管理文件系统映射到HTTP资源的代码。在STM32上,可以自己编写这部分代码,或者使用开源库,如uWSGI或ESP8266WebServer。 4. **硬件接口**:STM32需要...

    lightweight-search.zip

    它的核心组件可能包括索引构建模块、查询解析器、排名算法实现和结果展示逻辑,所有这些都封装在Java的lightweight-search.jar文件中。对于需要在有限资源环境下实现快速、准确搜索功能的项目,这样的工具是理想的...

    基于分布式配置中心配置限流参数的Redis轻量级分布式限流组件-lightweight-rate-limiter.zip

    在lightweight-rate-limiter中,配置中心可以是如Apollo、ConfigServer等,它使得限流参数可以根据业务需求动态调整,增强了系统的灵活性。 四、轻量级设计 轻量级限流组件强调的是低侵入性、易于集成和高效执行。...

    STM32H7FreeRTOS_LWIP_web_server_socket

    STM32H7FreeRTOS_LWIP_web_server_socket是一个基于STM32H7微控制器、FreeRTOS实时操作系统、LWIP轻量级网络协议栈的简单Web服务器实现。这个项目的核心是利用STM32的强大处理能力,通过FreeRTOS进行任务调度,结合...

    Lightweight Django

    Latest version of "Lightweight Django" Suitable if you've finished the official tutorial and re start Django research

    走进WindowsServer2008服务器核心(ServeCore)资料.pdf

    Server Core也支持部署和运行Active Directory Domain Services(AD DS)和Active Directory Lightweight Directory Services(AD LDS)。文档中提到了使用“netdom join”和“netdom remove”命令添加和移除域成员...

    CUBE_HTTP_SERVER_NETCONN.rar

    5. **处理HTTP请求**:在回调函数中,读取客户端发送的HTTP请求,解析请求头,根据请求类型(GET、POST等)执行相应的操作。 6. **响应处理**:根据请求,生成HTTP响应报文,包括状态码、响应头和内容。使用netconn...

    HTTP Proxy Server project

    Welcome to the HTTP ... This repository contains a lightweight and efficient HTTP proxy server implemented in C. The server acts as an intermediary for requests from clients seeking resources from other

    MIBS: A New Lightweight Block Cipher

    In this paper, we propose a new lightweight 64-bit block cipher, which we call MIBS, suitable for resource-constrained devices, such as low-cost RFID tags. We also study its hardware implementation ef...

    BES资料(Borland Enterprise Server)

    BEC参数通常包含在配置文件中,如server.xml,通过修改这些参数可以调整服务器的行为。例如,调整BEC的JDBC连接池参数可以优化数据库访问性能。 综上所述,BES是一个强大的企业级应用服务器,其丰富的特性和配置...

    轻量级人体姿态估计lightweight-human-pose-estimation.rar

    总的来说,“lightweight-human-pose-estimation.rar”项目揭示了深度学习在轻量化人体姿态估计中的实践,展现了AI技术如何帮助我们理解和解析复杂的人体运动。这不仅提升了相关领域的技术水平,也为未来的研究和...

    LightWeight IP Application Examples

    例如,通过调整内存分配、协议栈配置和接口参数,开发者可以优化内存使用,提升数据处理效率,减少延迟,并增加吞吐量,从而使得嵌入式设备在网络性能上达到预期表现。 此外,lwIP的多线程支持和可裁剪的设计也是其...

Global site tag (gtag.js) - Google Analytics