Using Mina to resolve HTTP protocol usage

Source: Internet
Author: User
Tags datetime integer socket
In the process of using Mina, we usually customize various messages to make it available for our own business. Today we will bring you a similar HTTP protocol decoding process.
The Mina has its own decoding class that resolves HTTP packets. You can use MAVEN to configure your content to get the source code:
<dependency>
    <groupId>org.apache.mina</groupId>
    <artifactid>mina-http</ artifactid>
    <version>3.0.0-M2</version>
</dependency>
or download the Mina source package to view the Org.apache.mina.http.HttpServerDecoder class. The following parsing methods are written for themselves:
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; /** * Decode HTTP protocol class * @author Herman.xiong * @date July 16, 2015 09:36:59 * @version V3.0 * @since tomcat6.0,jdk1.6 * @copyr ight Copyright (c) */public class Httpserverdecoder extends Cumulativeprotocoldecoder {private static final Logge

	R 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 (+). 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 ("test data, test data". 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);
			Body buf.putstring ("test data, test data", CE);
			Buf.putstring (LineDelimiter.CRLF.getValue (), CE);
			Buf.flip ();
			SYSTEM.OUT.PRINTLN ("The output is:" +buf.getstring (Charset.newdecoder ()));
			Buf.flip ();
		Socket.dodecode (Null,buf,null); }catch (Exception e) {E.printStackTrace ();  }}/** * Packet decoding */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 (+). 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]) &&Amp
    					Stringutils.isnotempty (Arr[1]) {map.put (arr[0],arr[1]);
    					} else {Log.error ("There is illegal content in the received packet!");
    						} 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") +ms
						g); 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"))) {s
			Ession.setattribute ("pocket", map);
		Session.setattribute ("Pocket_state", buf);
	} return false; }
	
}
You are welcome to follow my blog. If in doubt, please add QQ Group: 454796847 study together.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.