在使用mina的过程中,我们通常会自定义各种报文,以使用于自己的业务。今天就为大家带来一款类似http协议的解码过程。
mina有自带的解析http数据包的解码类。可以使用maven配置一下内容获取源码:

<dependency><groupId>org.apache.mina</groupId><artifactId>mina-http</artifactId><version>3.0.0-M2</version>
</dependency>

或者下载mina的源码包,查看org.apache.mina.http.HttpServerDecoder类。下面为自己写的解析方法:

package com.server;import java.lang.reflect.Method;
import java.nio.charset.Charset;import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.textline.LineDelimiter;/*** 解码HTTP协议类* @author Herman.xiong* @date 2015年7月16日09:36:59* @version V3.0* @since Tomcat6.0,Jdk1.6* @copyright Copyright (c) 2015*/
public class HttpServerDecoder extends CumulativeProtocolDecoder {private static final Logger log = Logger.getLogger(HttpServerDecoder.class);private LineDelimiter codecLineDelimiter = null;private Charset charset = null;private static final String MessageLength = "MessageLength";public HttpServerDecoder(Charset charset, LineDelimiter codecLineDelimiter) {this.charset = charset;this.codecLineDelimiter = codecLineDelimiter;}public Charset getCharset() {return charset;}public void setCharset(Charset charset) {this.charset = charset;}public LineDelimiter getCodecLineDelimiter() {return codecLineDelimiter;}public void setCodecLineDelimiter(LineDelimiter codecLineDelimiter) {this.codecLineDelimiter = codecLineDelimiter;}public static void main(String [] args){IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);Charset charset = Charset.forName("UTF-8");CharsetEncoder ce=charset.newEncoder();HttpServerDecoder socket=new HttpServerDecoder(Charset.forName("UTF-8"),LineDelimiter.CRLF);try{System.out.println("测试数据,测试数据".getBytes(charset).length);buf.putString("MessageMethod:UserAction", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("MessageType:GET", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("Content-Type:text/html; charset=iso-8859-1", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("Connection:keep-alive", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("Keep-Alive:200", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);         buf.putString("CompressType:jzip", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("Params:id=1&uid=2&name=3", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("accept-ranges:bytes", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("DateTime:DateTime", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.putString("MessageLength:27", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);//bodybuf.putString("测试数据,测试数据", ce);buf.putString(LineDelimiter.CRLF.getValue(), ce);buf.flip();System.out.println("输出的内容为:"+buf.getString(charset.newDecoder()));buf.flip();socket.doDecode(null,buf,null);}catch(Exception e){e.printStackTrace();}}/*** 数据包解码*/protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {Map<String,Object> map = (Map<String,Object>) session.getAttribute("pocket");IoBuffer buf = (IoBuffer)session.getAttribute("pocket_state");if(null ==buf)buf = IoBuffer.allocate(100).setAutoExpand(true).setAutoShrink(true);if(null == map)map = new HashMap<String,Object>();Integer len = 0;while (in.hasRemaining()) {len = 0;byte b = in.get();switch (b){case '\r':buf.put(b);break;case '\n':buf.put(b);buf.flip();String msg=buf.getString(charset.newDecoder());String[] arr = msg.split(":");if(StringUtils.isEmpty(map.get("MessageLength"))){if (2 == arr.length && StringUtils.isNotEmpty(arr[0]) && StringUtils.isNotEmpty(arr[1])) {map.put(arr[0],arr[1]);} else {log.error("收到的数据包中存在非法内容!");}if(Constant.HUPU_ZERO.equals(map.get("MessageLength"))){out.write(map);if(in.position()==in.limit()){session.setAttribute("pocket_state", null);session.setAttribute("pocket",null);return true;}map = new HashMap<String,Object>();}}else{map.put(StringUtils.isEmpty(map.get("MessageContent"))?msg:map.get("MessageContent")+msg);len=((null == map.get("MessageContent")) ? StringUtils.EMPTY : String.valueOf(map.get("MessageContent"))).getBytes(charset).length;if(len==Integer.parseInt(map.get("MessageContent"))+2){out.write(map);if(in.position()==in.limit()){session.setAttribute("pocket_state", null);session.setAttribute("pocket",null);return true;}}map = new HashMap<String,Object>();}buf.clear();break;default:buf.put(b);}}if(StringUtils.isEmpty(map.get("MessageLength")) || len<Integer.parseInt(map.get("MessageLength"))){session.setAttribute("pocket",map);session.setAttribute("pocket_state", buf);}return false;}}

欢迎大家关注我的博客!如有疑问,请加QQ群:454796847共同学习!

使用mina解析http协议的使用相关推荐

  1. 解析HTTP协议六种请求方法,get,head,put,delete,post有什么区别

    转载自  解析HTTP协议六种请求方法,get,head,put,delete,post有什么区别 标准Http协议支持六种请求方法,即: 1.GET 2.POST 3.PUT 4.Delete 5. ...

  2. 腐蚀rust服务器命令_【使用 Rust 写 Parser】2. 解析Redis协议

    系列所有文章 https://zhuanlan.zhihu.com/p/115017849​zhuanlan.zhihu.com https://zhuanlan.zhihu.com/p/139387 ...

  3. J8583CN解析ISO8583协议报文注意点

    最近在做POS接入涉及到如何正确解析ISO8583协议的问题,遇到了一些很讨厌的问题今天将他们总结一 下写在博客中,供大家参考. 1.  对于小白首先要了解什么是ISO8583协议,请参考该文章htt ...

  4. 【ATE-SENT协议】使用LabVIEW采集并解析SENT协议

    SENT协议大多用于车载行程传感器上,具体协议规范这里不讲,不了解的朋友可以看一下其他人的帖子.我这里只讲如何使用LabVIEW及NI硬件采集并解析SENT协议. 硬件采集方案 SENT协议的解析,物 ...

  5. FPGA解析串口协议帧3.0版本,增加了错误重发功能,提供仿真文件以及源码

    FPGA解析串口协议帧已经发布2个版本了,分别如下: 版本1:点击查看版本1 版本1详细介绍了串口协议帧的帧组成和设计思想,但设计粗糙,注释不详细: 版本1:点击查看版本2 版本2优化了代码,添加了详 ...

  6. lua语言学习之自定义wireshark插件来解析自定义协议

    lua语言学习之自定义wireshark插件来解析自定义协议 关于wireshark这个抓包工具 关于lua 使用lua写wireshark插件 wireshark接口文档 如何在wireshark使 ...

  7. 网卡解析arp协议导致ip address ** is already in ues for...

    2019独角兽企业重金招聘Python工程师标准>>> #service network restart Bringing up interface eth0:  Determini ...

  8. Java 面试知识点解析——网络协议篇

    Java 面试知识点解析--网络协议篇 前言: 在遨游了一番 Java Web 的世界之后,发现了自己的一些缺失,所以就着一篇深度好文:知名互联网公司校招 Java 开发岗面试知识点解析 ,来好好的对 ...

  9. python模拟gps定位_python解析nmea0183协议获取GPS定位信息

    python解析nmea0183协议获取GPS定位信息 nmea0183协议里面定位数据主要在GPRMC报文里面,下面是报文的大体形式: b'$GPRMC,111025.00,A,2517.03374 ...

最新文章

  1. bitmap对海量无重复的整数排序--转
  2. Spring Cloud Alibaba 生产实践:Sentinel 进阶应用场景
  3. 多线程的使用——模拟线程池的实现(2015-12-02 00:14:59)
  4. 若所有的参数皆需要类型转换——请为此采用non-member函数
  5. 想爱容易,相处难:当ASP.NET MVC爱上IoC
  6. 高盛发布区块链报告:从理论到实践(中文版)
  7. 节省3500万的背后,运维如何兼顾成本与效率?
  8. 如何使用批处理添加网络打印机
  9. 26岁,发25篇SCI,当上211教授、博导。
  10. java编程double相乘_浅谈Java double 相乘的结果偏差小问题
  11. 【bzoj1604】[Usaco2008 Open]Cow Neighborhoods 奶牛的邻居 旋转坐标系+并查集+Treap/STL-set...
  12. 三菱gxworks3安装失败_三菱gx works3下载 Gx Works3(三菱PLC编程软件) v1.031h 中文安装版(附安装教程+序列号) 下载-脚本之家...
  13. 面试经验|华为二面分享 真难ε=(´ο`*)))唉
  14. Bootstrap下拉单选框,下拉搜索多选框Bootstrap-select
  15. MongoDB 文档的高级查询操作
  16. java 音频 合成_java 音频 合成
  17. 蓝桥杯试题 基础练习 数列特征python
  18. 使用微信小程序新的订阅消息接口,主动推送。
  19. 一天一篇latex刘海洋代码解析:1.2.3填写正文
  20. memory check error at 0x03D70F16 = 0x00, should be 0xFD.

热门文章

  1. 图片转换成文字的方法
  2. go节假日execl导入
  3. css直角线_css3做圆角右边是圆角左边是直角?
  4. Python最简单的sklearn库安装教程
  5. 微信小程序实现代码高亮
  6. UE4在新的场景中调用AirSim
  7. APT攻击流程图画法参考
  8. 呼和浩特民族学院计算机系宿舍,【呼和浩特民族学院宿舍】呼和浩特民族学院有专科吗...
  9. 【第一阶段 day23 面向对象】构造方法 构造代码块与局部代码块 this
  10. .ne和php区别,深度剖析曝光松下吹风机ne62与wne6c哪个好?有什么区别?真实评测体验曝光...