分享

基于Mina的Http Server以及简单的Http请求客户端

 ricosxf 2014-07-24
     目的:
    Java平台下的内部组件之间的通信。
    1.WebService 由于感觉本身Java平台下的Web Service标准就不够统一,相互之间的调用就会有一些问题,更不用说与.net等其他平台了。而且WebService也是对HTTP请求的一次封装,效率上肯定会有损失,所以就不考虑用WebService了。
    2.Socket,包括Java原生的Socket API和nio,本身都很好,效率也会不错,它们之间的区别大概就是资源占用上了。但是使用Socket的通信,有几个比较复杂的地方是:1)协议解析,要订协议,解析及序列化2)粘包分包的处理(这个在长连接的情况下才会出现,可以不在考虑范围内)3)资源的管理,弄不好的话会导致CPU占用较高或者内存不知不觉泄露。
    3.HTTP通信。由于应用是独立的,不能依托于Web容器。Java原生的HttpServer API好像不推荐使用(藏在好深的一个包里com.sun.net.httpserver.*)。
    4.话说Mina的效率很高,是基于nio的异步通信,封装简化了好多。通过比较简单的包装就可以组成一个HTTP Server(下面例子中就是按照Mina官方提供的demo,自己改动了几点形成的)。然后HTTP的Client端也随便封装下就是了。

步骤
1.封装HTTP请求消息类和响应消息类
Java代码  收藏代码
  1. package com.ajita.httpserver;  
  2.   
  3. import java.util.Map;  
  4. import java.util.Map.Entry;  
  5.   
  6. /** 
  7.  * 使用Mina解析出的HTTP请求对象 
  8.  *  
  9.  * @author Ajita 
  10.  *  
  11.  */  
  12. public class HttpRequestMessage {  
  13.     /** 
  14.      * HTTP请求的主要属性及内容 
  15.      */  
  16.     private Map<String, String[]> headers = null;  
  17.   
  18.     public Map<String, String[]> getHeaders() {  
  19.         return headers;  
  20.     }  
  21.   
  22.     public void setHeaders(Map<String, String[]> headers) {  
  23.         this.headers = headers;  
  24.     }  
  25.   
  26.     /** 
  27.      * 获取HTTP请求的Context信息 
  28.      */  
  29.     public String getContext() {  
  30.         String[] context = headers.get("Context");  
  31.         return context == null ? "" : context[0];  
  32.     }  
  33.   
  34.     /** 
  35.      * 根据属性名称获得属性值数组第一个值,用于在url中传递的参数 
  36.      */  
  37.     public String getParameter(String name) {  
  38.         String[] param = headers.get("@".concat(name));  
  39.         return param == null ? "" : param[0];  
  40.     }  
  41.   
  42.     /** 
  43.      * 根据属性名称获得属性值,用于在url中传递的参数 
  44.      */  
  45.     public String[] getParameters(String name) {  
  46.         String[] param = headers.get("@".concat(name));  
  47.         return param == null ? new String[] {} : param;  
  48.     }  
  49.   
  50.     /** 
  51.      * 根据属性名称获得属性值,用于请求的特征参数 
  52.      */  
  53.     public String[] getHeader(String name) {  
  54.         return headers.get(name);  
  55.     }  
  56.   
  57.     @Override  
  58.     public String toString() {  
  59.         StringBuilder str = new StringBuilder();  
  60.   
  61.         for (Entry<String, String[]> e : headers.entrySet()) {  
  62.             str.append(e.getKey() + " : " + arrayToString(e.getValue(), ',')  
  63.                     + "\n");  
  64.         }  
  65.         return str.toString();  
  66.     }  
  67.   
  68.     /** 
  69.      * 静态方法,用来把一个字符串数组拼接成一个字符串 
  70.      *  
  71.      * @param s要拼接的字符串数组 
  72.      * @param sep数据元素之间的烦恼歌负 
  73.      * @return 拼接成的字符串 
  74.      */  
  75.     public static String arrayToString(String[] s, char sep) {  
  76.         if (s == null || s.length == 0) {  
  77.             return "";  
  78.         }  
  79.         StringBuffer buf = new StringBuffer();  
  80.         if (s != null) {  
  81.             for (int i = 0; i < s.length; i++) {  
  82.                 if (i > 0) {  
  83.                     buf.append(sep);  
  84.                 }  
  85.                 buf.append(s[i]);  
  86.             }  
  87.         }  
  88.         return buf.toString();  
  89.     }  
  90.   
  91. }  
  92.   
  93. package com.ajita.httpserver;  
  94.   
  95.   
  96. import java.io.ByteArrayOutputStream;  
  97. import java.io.IOException;  
  98. import java.text.SimpleDateFormat;  
  99. import java.util.Date;  
  100. import java.util.HashMap;  
  101. import java.util.Map;  
  102.   
  103. import org.apache.mina.core.buffer.IoBuffer;  
  104.   
  105. public class HttpResponseMessage {  
  106.     /** HTTP response codes */  
  107.     public static final int HTTP_STATUS_SUCCESS = 200;  
  108.   
  109.     public static final int HTTP_STATUS_NOT_FOUND = 404;  
  110.   
  111.     /** Map<String, String> */  
  112.     private final Map<String, String> headers = new HashMap<String, String>();  
  113.   
  114.     /** Storage for body of HTTP response. */  
  115.     private final ByteArrayOutputStream body = new ByteArrayOutputStream(1024);  
  116.   
  117.     private int responseCode = HTTP_STATUS_SUCCESS;  
  118.   
  119.     public HttpResponseMessage() {  
  120.         // headers.put("Server", "HttpServer (" + Server.VERSION_STRING + ')');  
  121.         headers.put("Server", "HttpServer (" + "Mina 2.0" + ')');  
  122.         headers.put("Cache-Control", "private");  
  123.         headers.put("Content-Type", "text/html; charset=iso-8859-1");  
  124.         headers.put("Connection", "keep-alive");  
  125.         headers.put("Keep-Alive", "200");  
  126.         headers.put("Date", new SimpleDateFormat(  
  127.                 "EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date()));  
  128.         headers.put("Last-Modified", new SimpleDateFormat(  
  129.                 "EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date()));  
  130.     }  
  131.   
  132.     public Map<String, String> getHeaders() {  
  133.         return headers;  
  134.     }  
  135.   
  136.     public void setContentType(String contentType) {  
  137.         headers.put("Content-Type", contentType);  
  138.     }  
  139.   
  140.     public void setResponseCode(int responseCode) {  
  141.         this.responseCode = responseCode;  
  142.     }  
  143.   
  144.     public int getResponseCode() {  
  145.         return this.responseCode;  
  146.     }  
  147.   
  148.     public void appendBody(byte[] b) {  
  149.         try {  
  150.             body.write(b);  
  151.         } catch (IOException ex) {  
  152.             ex.printStackTrace();  
  153.         }  
  154.     }  
  155.   
  156.     public void appendBody(String s) {  
  157.         try {  
  158.             body.write(s.getBytes());  
  159.         } catch (IOException ex) {  
  160.             ex.printStackTrace();  
  161.         }  
  162.     }  
  163.   
  164.     public IoBuffer getBody() {  
  165.         return IoBuffer.wrap(body.toByteArray());  
  166.     }  
  167.   
  168.     public int getBodyLength() {  
  169.         return body.size();  
  170.     }  
  171.   
  172. }  

2.封装Mina的解析HTTP请求和发送HTTP响应的编码类和解码类
Java代码  收藏代码
  1. package com.ajita.httpserver;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.StringReader;  
  6. import java.nio.charset.CharacterCodingException;  
  7. import java.nio.charset.Charset;  
  8. import java.nio.charset.CharsetDecoder;  
  9. import java.util.HashMap;  
  10. import java.util.Map;  
  11.   
  12. import org.apache.mina.core.buffer.IoBuffer;  
  13. import org.apache.mina.core.session.IoSession;  
  14. import org.apache.mina.filter.codec.ProtocolDecoderOutput;  
  15. import org.apache.mina.filter.codec.demux.MessageDecoderAdapter;  
  16. import org.apache.mina.filter.codec.demux.MessageDecoderResult;  
  17.   
  18. public class HttpRequestDecoder extends MessageDecoderAdapter {  
  19.     private static final byte[] CONTENT_LENGTH = new String("Content-Length:")  
  20.             .getBytes();  
  21.     static String defaultEncoding;  
  22.     private CharsetDecoder decoder;  
  23.   
  24.     public CharsetDecoder getDecoder() {  
  25.         return decoder;  
  26.     }  
  27.   
  28.     public void setEncoder(CharsetDecoder decoder) {  
  29.         this.decoder = decoder;  
  30.     }  
  31.   
  32.     private HttpRequestMessage request = null;  
  33.   
  34.     public HttpRequestDecoder() {  
  35.         decoder = Charset.forName(defaultEncoding).newDecoder();  
  36.     }  
  37.   
  38.     public MessageDecoderResult decodable(IoSession session, IoBuffer in) {  
  39.         try {  
  40.             return messageComplete(in) ? MessageDecoderResult.OK  
  41.                     : MessageDecoderResult.NEED_DATA;  
  42.         } catch (Exception ex) {  
  43.             ex.printStackTrace();  
  44.         }  
  45.   
  46.         return MessageDecoderResult.NOT_OK;  
  47.     }  
  48.   
  49.     public MessageDecoderResult decode(IoSession session, IoBuffer in,  
  50.             ProtocolDecoderOutput out) throws Exception {  
  51.         HttpRequestMessage m = decodeBody(in);  
  52.   
  53.         // Return NEED_DATA if the body is not fully read.  
  54.         if (m == null) {  
  55.             return MessageDecoderResult.NEED_DATA;  
  56.         }  
  57.   
  58.         out.write(m);  
  59.   
  60.         return MessageDecoderResult.OK;  
  61.   
  62.     }  
  63.   
  64.     /* 
  65.      * 判断HTTP请求是否完整,若格式有错误直接抛出异常 
  66.      */  
  67.     private boolean messageComplete(IoBuffer in) {  
  68.         int last = in.remaining() - 1;  
  69.         if (in.remaining() < 4) {  
  70.             return false;  
  71.         }  
  72.   
  73.         // to speed up things we check if the Http request is a GET or POST  
  74.         if (in.get(0) == (byte) 'G' && in.get(1) == (byte) 'E'  
  75.                 && in.get(2) == (byte) 'T') {  
  76.             // Http GET request therefore the last 4 bytes should be 0x0D 0x0A  
  77.             // 0x0D 0x0A  
  78.             return in.get(last) == (byte) 0x0A  
  79.                     && in.get(last - 1) == (byte) 0x0D  
  80.                     && in.get(last - 2) == (byte) 0x0A  
  81.                     && in.get(last - 3) == (byte) 0x0D;  
  82.         } else if (in.get(0) == (byte) 'P' && in.get(1) == (byte) 'O'  
  83.                 && in.get(2) == (byte) 'S' && in.get(3) == (byte) 'T') {  
  84.             // Http POST request  
  85.             // first the position of the 0x0D 0x0A 0x0D 0x0A bytes  
  86.             int eoh = -1;  
  87.             for (int i = last; i > 2; i--) {  
  88.                 if (in.get(i) == (byte) 0x0A && in.get(i - 1) == (byte) 0x0D  
  89.                         && in.get(i - 2) == (byte) 0x0A  
  90.                         && in.get(i - 3) == (byte) 0x0D) {  
  91.                     eoh = i + 1;  
  92.                     break;  
  93.                 }  
  94.             }  
  95.             if (eoh == -1) {  
  96.                 return false;  
  97.             }  
  98.             for (int i = 0; i < last; i++) {  
  99.                 boolean found = false;  
  100.                 for (int j = 0; j < CONTENT_LENGTH.length; j++) {  
  101.                     if (in.get(i + j) != CONTENT_LENGTH[j]) {  
  102.                         found = false;  
  103.                         break;  
  104.                     }  
  105.                     found = true;  
  106.                 }  
  107.                 if (found) {  
  108.                     // retrieve value from this position till next 0x0D 0x0A  
  109.                     StringBuilder contentLength = new StringBuilder();  
  110.                     for (int j = i + CONTENT_LENGTH.length; j < last; j++) {  
  111.                         if (in.get(j) == 0x0D) {  
  112.                             break;  
  113.                         }  
  114.                         contentLength.append(new String(  
  115.                                 new byte[] { in.get(j) }));  
  116.                     }  
  117.                     // if content-length worth of data has been received then  
  118.                     // the message is complete  
  119.                     return Integer.parseInt(contentLength.toString().trim())  
  120.                             + eoh == in.remaining();  
  121.                 }  
  122.             }  
  123.         }  
  124.   
  125.         // the message is not complete and we need more data  
  126.         return false;  
  127.   
  128.     }  
  129.   
  130.     private HttpRequestMessage decodeBody(IoBuffer in) {  
  131.         request = new HttpRequestMessage();  
  132.         try {  
  133.             request.setHeaders(parseRequest(new StringReader(in  
  134.                     .getString(decoder))));  
  135.             return request;  
  136.         } catch (CharacterCodingException ex) {  
  137.             ex.printStackTrace();  
  138.         }  
  139.   
  140.         return null;  
  141.   
  142.     }  
  143.   
  144.     private Map<String, String[]> parseRequest(StringReader is) {  
  145.         Map<String, String[]> map = new HashMap<String, String[]>();  
  146.         BufferedReader rdr = new BufferedReader(is);  
  147.   
  148.         try {  
  149.             // Get request URL.  
  150.             String line = rdr.readLine();  
  151.             String[] url = line.split(" ");  
  152.             if (url.length < 3) {  
  153.                 return map;  
  154.             }  
  155.   
  156.             map.put("URI", new String[] { line });  
  157.             map.put("Method", new String[] { url[0].toUpperCase() });  
  158.             map.put("Context", new String[] { url[1].substring(1) });  
  159.             map.put("Protocol", new String[] { url[2] });  
  160.             // Read header  
  161.             while ((line = rdr.readLine()) != null && line.length() > 0) {  
  162.                 String[] tokens = line.split(": ");  
  163.                 map.put(tokens[0], new String[] { tokens[1] });  
  164.             }  
  165.   
  166.             // If method 'POST' then read Content-Length worth of data  
  167.             if (url[0].equalsIgnoreCase("POST")) {  
  168.                 int len = Integer.parseInt(map.get("Content-Length")[0]);  
  169.                 char[] buf = new char[len];  
  170.                 if (rdr.read(buf) == len) {  
  171.                     line = String.copyValueOf(buf);  
  172.                 }  
  173.             } else if (url[0].equalsIgnoreCase("GET")) {  
  174.                 int idx = url[1].indexOf('?');  
  175.                 if (idx != -1) {  
  176.                     map.put("Context",  
  177.                             new String[] { url[1].substring(1, idx) });  
  178.                     line = url[1].substring(idx + 1);  
  179.                 } else {  
  180.                     line = null;  
  181.                 }  
  182.             }  
  183.             if (line != null) {  
  184.                 String[] match = line.split("\\&");  
  185.                 for (String element : match) {  
  186.                     String[] params = new String[1];  
  187.                     String[] tokens = element.split("=");  
  188.                     switch (tokens.length) {  
  189.                     case 0:  
  190.                         map.put("@".concat(element), new String[] {});  
  191.                         break;  
  192.                     case 1:  
  193.                         map.put("@".concat(tokens[0]), new String[] {});  
  194.                         break;  
  195.                     default:  
  196.                         String name = "@".concat(tokens[0]);  
  197.                         if (map.containsKey(name)) {  
  198.                             params = map.get(name);  
  199.                             String[] tmp = new String[params.length + 1];  
  200.                             for (int j = 0; j < params.length; j++) {  
  201.                                 tmp[j] = params[j];  
  202.                             }  
  203.                             params = null;  
  204.                             params = tmp;  
  205.                         }  
  206.                         params[params.length - 1] = tokens[1].trim();  
  207.                         map.put(name, params);  
  208.                     }  
  209.                 }  
  210.             }  
  211.         } catch (IOException ex) {  
  212.             ex.printStackTrace();  
  213.         }  
  214.   
  215.         return map;  
  216.     }  
  217.   
  218. }  
  219. package com.ajita.httpserver;  
  220.   
  221.   
  222. import java.io.ByteArrayOutputStream;  
  223. import java.io.IOException;  
  224. import java.text.SimpleDateFormat;  
  225. import java.util.Date;  
  226. import java.util.HashMap;  
  227. import java.util.Map;  
  228.   
  229. import org.apache.mina.core.buffer.IoBuffer;  
  230.   
  231. public class HttpResponseMessage {  
  232.     /** HTTP response codes */  
  233.     public static final int HTTP_STATUS_SUCCESS = 200;  
  234.   
  235.     public static final int HTTP_STATUS_NOT_FOUND = 404;  
  236.   
  237.     /** Map<String, String> */  
  238.     private final Map<String, String> headers = new HashMap<String, String>();  
  239.   
  240.     /** Storage for body of HTTP response. */  
  241.     private final ByteArrayOutputStream body = new ByteArrayOutputStream(1024);  
  242.   
  243.     private int responseCode = HTTP_STATUS_SUCCESS;  
  244.   
  245.     public HttpResponseMessage() {  
  246.         // headers.put("Server", "HttpServer (" + Server.VERSION_STRING + ')');  
  247.         headers.put("Server", "HttpServer (" + "Mina 2.0" + ')');  
  248.         headers.put("Cache-Control", "private");  
  249.         headers.put("Content-Type", "text/html; charset=iso-8859-1");  
  250.         headers.put("Connection", "keep-alive");  
  251.         headers.put("Keep-Alive", "200");  
  252.         headers.put("Date", new SimpleDateFormat(  
  253.                 "EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date()));  
  254.         headers.put("Last-Modified", new SimpleDateFormat(  
  255.                 "EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date()));  
  256.     }  
  257.   
  258.     public Map<String, String> getHeaders() {  
  259.         return headers;  
  260.     }  
  261.   
  262.     public void setContentType(String contentType) {  
  263.         headers.put("Content-Type", contentType);  
  264.     }  
  265.   
  266.     public void setResponseCode(int responseCode) {  
  267.         this.responseCode = responseCode;  
  268.     }  
  269.   
  270.     public int getResponseCode() {  
  271.         return this.responseCode;  
  272.     }  
  273.   
  274.     public void appendBody(byte[] b) {  
  275.         try {  
  276.             body.write(b);  
  277.         } catch (IOException ex) {  
  278.             ex.printStackTrace();  
  279.         }  
  280.     }  
  281.   
  282.     public void appendBody(String s) {  
  283.         try {  
  284.             body.write(s.getBytes());  
  285.         } catch (IOException ex) {  
  286.             ex.printStackTrace();  
  287.         }  
  288.     }  
  289.   
  290.     public IoBuffer getBody() {  
  291.         return IoBuffer.wrap(body.toByteArray());  
  292.     }  
  293.   
  294.     public int getBodyLength() {  
  295.         return body.size();  
  296.     }  
  297.   
  298. }  

3.封装HTTP的Server类及HTTP的Handler处理接口,其中HttpHandler接口是要暴露给外部就行自定义处理的。
Java代码  收藏代码
  1. package com.ajita.httpserver;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import org.apache.mina.filter.codec.ProtocolCodecFilter;  
  7. import org.apache.mina.filter.logging.LoggingFilter;  
  8. import org.apache.mina.transport.socket.nio.NioSocketAcceptor;  
  9.   
  10. public class HttpServer {  
  11.     /** Default HTTP port */  
  12.     private static final int DEFAULT_PORT = 8080;  
  13.     private NioSocketAcceptor acceptor;  
  14.     private boolean isRunning;  
  15.   
  16.     private String encoding;  
  17.     private HttpHandler httpHandler;  
  18.   
  19.     public String getEncoding() {  
  20.         return encoding;  
  21.     }  
  22.   
  23.     public void setEncoding(String encoding) {  
  24.         this.encoding = encoding;  
  25.         HttpRequestDecoder.defaultEncoding = encoding;  
  26.         HttpResponseEncoder.defaultEncoding = encoding;  
  27.     }  
  28.   
  29.     public HttpHandler getHttpHandler() {  
  30.         return httpHandler;  
  31.     }  
  32.   
  33.     public void setHttpHandler(HttpHandler httpHandler) {  
  34.         this.httpHandler = httpHandler;  
  35.     }  
  36.   
  37.     /** 
  38.      * 启动HTTP服务端箭筒HTTP请求 
  39.      *  
  40.      * @param port要监听的端口号 
  41.      * @throws IOException 
  42.      */  
  43.     public void run(int port) throws IOException {  
  44.         synchronized (this) {  
  45.             if (isRunning) {  
  46.                 System.out.println("Server is already running.");  
  47.                 return;  
  48.             }  
  49.             acceptor = new NioSocketAcceptor();  
  50.             acceptor.getFilterChain().addLast(  
  51.                     "protocolFilter",  
  52.                     new ProtocolCodecFilter(  
  53.                             new HttpServerProtocolCodecFactory()));  
  54.             // acceptor.getFilterChain().addLast("logger", new LoggingFilter());  
  55.             ServerHandler handler = new ServerHandler();  
  56.             handler.setHandler(httpHandler);  
  57.             acceptor.setHandler(handler);  
  58.             acceptor.bind(new InetSocketAddress(port));  
  59.             isRunning = true;  
  60.             System.out.println("Server now listening on port " + port);  
  61.         }  
  62.     }  
  63.   
  64.     /** 
  65.      * 使用默认端口8080 
  66.      *  
  67.      * @throws IOException 
  68.      */  
  69.     public void run() throws IOException {  
  70.         run(DEFAULT_PORT);  
  71.     }  
  72.   
  73.     /** 
  74.      * 停止监听HTTP服务 
  75.      */  
  76.     public void stop() {  
  77.         synchronized (this) {  
  78.             if (!isRunning) {  
  79.                 System.out.println("Server is already stoped.");  
  80.                 return;  
  81.             }  
  82.             isRunning = false;  
  83.             try {  
  84.                 acceptor.unbind();  
  85.                 acceptor.dispose();  
  86.                 System.out.println("Server is stoped.");  
  87.             } catch (Exception e) {  
  88.                 e.printStackTrace();  
  89.             }  
  90.         }  
  91.     }  
  92.   
  93.     public static void main(String[] args) {  
  94.         int port = DEFAULT_PORT;  
  95.   
  96.         for (int i = 0; i < args.length; i++) {  
  97.             if (args[i].equals("-port")) {  
  98.                 port = Integer.parseInt(args[i + 1]);  
  99.             }  
  100.         }  
  101.   
  102.         try {  
  103.             // Create an acceptor  
  104.             NioSocketAcceptor acceptor = new NioSocketAcceptor();  
  105.   
  106.             // Create a service configuration  
  107.             acceptor.getFilterChain().addLast(  
  108.                     "protocolFilter",  
  109.                     new ProtocolCodecFilter(  
  110.                             new HttpServerProtocolCodecFactory()));  
  111.             acceptor.getFilterChain().addLast("logger", new LoggingFilter());  
  112.             acceptor.setHandler(new ServerHandler());  
  113.             acceptor.bind(new InetSocketAddress(port));  
  114.   
  115.             System.out.println("Server now listening on port " + port);  
  116.         } catch (Exception ex) {  
  117.             ex.printStackTrace();  
  118.         }  
  119.     }  
  120. }  
  121.   
  122. package com.ajita.httpserver;  
  123.   
  124. import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory;  
  125.   
  126. public class HttpServerProtocolCodecFactory extends  
  127.         DemuxingProtocolCodecFactory {  
  128.     public HttpServerProtocolCodecFactory() {  
  129.         super.addMessageDecoder(HttpRequestDecoder.class);  
  130.         super.addMessageEncoder(HttpResponseMessage.class,  
  131.                 HttpResponseEncoder.class);  
  132.     }  
  133.   
  134. }  
  135.   
  136. package com.ajita.httpserver;  
  137.   
  138. import org.apache.mina.core.future.IoFutureListener;  
  139. import org.apache.mina.core.service.IoHandlerAdapter;  
  140. import org.apache.mina.core.session.IdleStatus;  
  141. import org.apache.mina.core.session.IoSession;  
  142.   
  143. public class ServerHandler extends IoHandlerAdapter {  
  144.     private HttpHandler handler;  
  145.   
  146.     public HttpHandler getHandler() {  
  147.         return handler;  
  148.     }  
  149.   
  150.     public void setHandler(HttpHandler handler) {  
  151.         this.handler = handler;  
  152.     }  
  153.   
  154.     @Override  
  155.     public void sessionOpened(IoSession session) {  
  156.         // set idle time to 60 seconds  
  157.         session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);  
  158.     }  
  159.   
  160.     @Override  
  161.     public void messageReceived(IoSession session, Object message) {  
  162.         // Check that we can service the request context  
  163.         HttpRequestMessage request = (HttpRequestMessage) message;  
  164.         HttpResponseMessage response = handler.handle(request);  
  165.         // HttpResponseMessage response = new HttpResponseMessage();  
  166.         // response.setContentType("text/plain");  
  167.         // response.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS);  
  168.         // response.appendBody("CONNECTED");  
  169.   
  170.         // msg.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS);  
  171.         // byte[] b = new byte[ta.buffer.limit()];  
  172.         // ta.buffer.rewind().get(b);  
  173.         // msg.appendBody(b);  
  174.         // System.out.println("####################");  
  175.         // System.out.println("  GET_TILE RESPONSE SENT - ATTACHMENT GOOD DIAMOND.SI="+d.si+  
  176.         // ", "+new  
  177.         // java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss.SSS").format(new  
  178.         // java.util.Date()));  
  179.         // System.out.println("#################### - status="+ta.state+", index="+message.getIndex());  
  180.   
  181.         // // Unknown request  
  182.         // response = new HttpResponseMessage();  
  183.         // response.setResponseCode(HttpResponseMessage.HTTP_STATUS_NOT_FOUND);  
  184.         // response.appendBody(String.format(  
  185.         // "<html><body><h1>UNKNOWN REQUEST %d</h1></body></html>",  
  186.         // HttpResponseMessage.HTTP_STATUS_NOT_FOUND));  
  187.   
  188.         if (response != null) {  
  189.             session.write(response).addListener(IoFutureListener.CLOSE);  
  190.         }  
  191.     }  
  192.   
  193.     @Override  
  194.     public void sessionIdle(IoSession session, IdleStatus status) {  
  195.         session.close(false);  
  196.     }  
  197.   
  198.     @Override  
  199.     public void exceptionCaught(IoSession session, Throwable cause) {  
  200.         session.close(false);  
  201.     }  
  202. }  
  203.   
  204. package com.ajita.httpserver;  
  205.   
  206. /** 
  207.  * HTTP请求的处理接口 
  208.  *  
  209.  * @author Ajita 
  210.  *  
  211.  */  
  212. public interface HttpHandler {  
  213.     /** 
  214.      * 自定义HTTP请求处理需要实现的方法 
  215.      * @param request 一个HTTP请求对象 
  216.      * @return HTTP请求处理后的返回结果 
  217.      */  
  218.     HttpResponseMessage handle(HttpRequestMessage request);  
  219. }  


4.HTTP Client端,网上一抓一大把,就不说了

5.测试
建立测试类如下
Java代码  收藏代码
  1. package com.jita;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.ajita.httpserver.HttpHandler;  
  6. import com.ajita.httpserver.HttpRequestMessage;  
  7. import com.ajita.httpserver.HttpResponseMessage;  
  8. import com.ajita.httpserver.HttpServer;  
  9.   
  10. public class TestHttpServer {  
  11.     public static void main(String[] args) throws IOException,  
  12.             InterruptedException {  
  13.         HttpServer server = new HttpServer();  
  14.         server.setEncoding("GB2312");  
  15.         server.setHttpHandler(new HttpHandler() {  
  16.             public HttpResponseMessage handle(HttpRequestMessage request) {  
  17.                 String level = request.getParameter("level");  
  18.                 System.out.println(request.getParameter("level"));  
  19.                 System.out.println(request.getContext());  
  20.                 HttpResponseMessage response = new HttpResponseMessage();  
  21.                 response.setContentType("text/plain");  
  22.                 response.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS);  
  23.                 response.appendBody("CONNECTED\n");  
  24.                 response.appendBody(level);  
  25.                 return response;  
  26.             }  
  27.         });  
  28.         server.run();  
  29.   
  30.         //Thread.sleep(10000);  
  31.         // server.stop();  
  32.     }  
  33. }  


启动,在浏览器中输入HTTP请求如:http://192.168.13.242:8080/test.do?level=aaa


附件是完整的代码。 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多