Netty處理HTTP之GET,POST請求
Netty處理HTTP之GET,POST請求
這里使用瀏覽器發出http請求,也可以使用netty寫http的客戶端。從瀏覽器請求http://localhost:8080/,服務器會生成兩個form表單,一個form表單是get請求,一個是post請求,經過netty的request解碼器,封裝成HttpObject對象,判斷對象是否是HttpRequest對象,是的話執行代碼。
注:瀏覽器發出的/favicon.ico請求
瀏覽器調用favicon的原理是首先在網頁所在目錄尋找favicon.ico文件,如果沒有找到就去網站的根目錄尋找。所以最簡單的方法就是將制作好的favicon文件命名為favicon.ico然后上傳到網站的根目錄下。
Netty的http對象都是Netty自己封裝的,不是標準的。
先看http的服務器端。服務器的代碼一般就是這樣。
package http.lyx3;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* A HTTP server showing how to use the HTTP multipart package for file uploads.
*/
public class HttpDemoServer {
private final int port;
public static boolean isSSL;
public HttpDemoServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new HttpDemoServerInitializer());
Channel ch = b.bind(port).sync().channel();
System.out.println("HTTP Upload Server at port " + port + '.');
System.out.println("Open your browser and navigate to http://localhost:" + port + '/');
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
if (args.length > 1) {
isSSL = true;
}
new HttpDemoServer(port).run();
}
} 初始化服務器端handler的代碼
package http.lyx3;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;
import securechat.SecureChatSslContextFactory;
import javax.net.ssl.SSLEngine;
public class HttpDemoServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = ch.pipeline();
if (HttpDemoServer.isSSL) {
SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
}
/**
* http-request解碼器
* http服務器端對request解碼
*/
pipeline.addLast("decoder", new HttpRequestDecoder());
/**
* http-response解碼器
* http服務器端對response編碼
*/
pipeline.addLast("encoder", new HttpResponseEncoder());
/**
* 壓縮
* Compresses an HttpMessage and an HttpContent in gzip or deflate encoding
* while respecting the "Accept-Encoding" header.
* If there is no matching encoding, no compression is done.
*/
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("handler", new HttpDemoServerHandler());
}
}
最重要的是handler,處理http請求,返回http響應(返回響應給瀏覽器)
package http.lyx3;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDecoderException;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static io.netty.buffer.Unpooled.copiedBuffer;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
public class HttpDemoServerHandler extends SimpleChannelInboundHandler<HttpObject> {
private HttpRequest request;
private boolean readingChunks;
private final StringBuilder responseContent = new StringBuilder();
private static final HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); //Disk
private HttpPostRequestDecoder decoder;
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (decoder != null) {
decoder.cleanFiles();
}
}
public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
System.err.println(msg.getClass().getName());
/**
* msg的類型
* {@link DefaultHttpRequest}
* {@link LastHttpContent}
*/
if (msg instanceof HttpRequest) {
HttpRequest request = this.request = (HttpRequest) msg;
URI uri = new URI(request.getUri());
System.err.println("request uri==" + uri.getPath());
if (uri.getPath().equals("/favicon.ico")) {
return;
}
if (uri.getPath().equals("/")) {
writeMenu(ctx);
return;
}
responseContent.setLength(0);
responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
responseContent.append("===================================\r\n");
responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");
responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
responseContent.append("\r\n\r\n");
// new getMethod
for (Entry<String, String> entry : request.headers()) {
responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
}
responseContent.append("\r\n\r\n");
// new getMethod
Set<Cookie> cookies;
String value = request.headers().get(COOKIE);
if (value == null) {
/**
* Returns an empty set (immutable).
*/
cookies = Collections.emptySet();
} else {
cookies = CookieDecoder.decode(value);
}
for (Cookie cookie : cookies) {
responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
}
responseContent.append("\r\n\r\n");
/**
* List<String>表示當參數相同時,把相同的參數的值放在list中
*/
QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
Map<String, List<String>> uriAttributes = decoderQuery.parameters();
for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
for (String attrVal : attr.getValue()) {
responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
}
}
responseContent.append("\r\n\r\n");
// if GET Method: should not try to create a HttpPostRequestDecoder
if (request.getMethod().equals(HttpMethod.GET)) {
// GET Method: should not try to create a HttpPostRequestDecoder
// So stop here
responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
writeResponse(ctx.channel());
return;
}
//判斷request請求是否是post請求
if (request.getMethod().equals(HttpMethod.POST)) {
System.err.println("===this is http post===");
try {
/**
* 通過HttpDataFactory和request構造解碼器
*/
decoder = new HttpPostRequestDecoder(factory, request);
} catch (ErrorDataDecoderException e1) {
e1.printStackTrace();
responseContent.append(e1.getMessage());
writeResponse(ctx.channel());
ctx.channel().close();
return;
}
readingChunks = HttpHeaders.isTransferEncodingChunked(request);
responseContent.append("Is Chunked: " + readingChunks + "\r\n");
responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
if (readingChunks) {
// Chunk version
responseContent.append("Chunks: ");
readingChunks = true;
}
}
}
if (decoder != null) {
if (msg instanceof HttpContent) {
// New chunk is received
HttpContent chunk = (HttpContent) msg;
try {
decoder.offer(chunk);
} catch (ErrorDataDecoderException e1) {
e1.printStackTrace();
responseContent.append(e1.getMessage());
writeResponse(ctx.channel());
ctx.channel().close();
return;
}
responseContent.append('o');
try {
while (decoder.hasNext()) {
InterfaceHttpData data = decoder.next();
if (data != null) {
try {
writeHttpData(data);
} finally {
data.release();
}
}
}
} catch (EndOfDataDecoderException e1) {
responseContent.append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n");
}
// example of reading only if at the end
if (chunk instanceof LastHttpContent) {
writeResponse(ctx.channel());
readingChunks = false;
reset();
}
}
}
}
private void reset() {
request = null;
// destroy the decoder to release all resources
decoder.destroy();
decoder = null;
}
private void writeHttpData(InterfaceHttpData data) {
/**
* HttpDataType有三種類型
* Attribute, FileUpload, InternalAttribute
*/
if (data.getHttpDataType() == HttpDataType.Attribute) {
Attribute attribute = (Attribute) data;
String value;
try {
value = attribute.getValue();
} catch (IOException e1) {
e1.printStackTrace();
responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ":"
+ attribute.getName() + " Error while reading value: " + e1.getMessage() + "\r\n");
return;
}
if (value.length() > 100) {
responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ":"
+ attribute.getName() + " data too long\r\n");
} else {
responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ":"
+ attribute.toString() + "\r\n");
}
}
}
private void writeResponse(Channel channel) {
// Convert the response content to a ChannelBuffer.
ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
responseContent.setLength(0);
// Decide whether to close the connection or not.
boolean close = request.headers().contains(CONNECTION, HttpHeaders.Values.CLOSE, true)
|| request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
&& !request.headers().contains(CONNECTION, HttpHeaders.Values.KEEP_ALIVE, true);
// Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
if (!close) {
// There's no need to add 'Content-Length' header
// if this is the last response.
response.headers().set(CONTENT_LENGTH, buf.readableBytes());
}
Set<Cookie> cookies;
String value = request.headers().get(COOKIE);
if (value == null) {
cookies = Collections.emptySet();
} else {
cookies = CookieDecoder.decode(value);
}
if (!cookies.isEmpty()) {
// Reset the cookies if necessary.
for (Cookie cookie : cookies) {
response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
}
}
// Write the response.
ChannelFuture future = channel.writeAndFlush(response);
// Close the connection after the write operation is done if necessary.
if (close) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
private void writeMenu(ChannelHandlerContext ctx) {
// print several HTML forms
// Convert the response content to a ChannelBuffer.
responseContent.setLength(0);
// create Pseudo Menu
responseContent.append("<html>");
responseContent.append("<head>");
responseContent.append("<title>Netty Test Form</title>\r\n");
responseContent.append("</head>\r\n");
responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>");
responseContent.append("<table border=\"0\">");
responseContent.append("<tr>");
responseContent.append("<td>");
responseContent.append("<h1>Netty Test Form</h1>");
responseContent.append("Choose one FORM");
responseContent.append("</td>");
responseContent.append("</tr>");
responseContent.append("</table>\r\n");
// GET
responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
responseContent.append("<FORM ACTION=\"/from-get\" METHOD=\"GET\">");
responseContent.append("<input type=hidden name=getform value=\"GET\">");
responseContent.append("<table border=\"0\">");
responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
responseContent
.append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
responseContent.append("</td></tr>");
responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
responseContent.append("</table></FORM>\r\n");
responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
// POST
responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
responseContent.append("<FORM ACTION=\"/from-post\" METHOD=\"POST\">");
responseContent.append("<input type=hidden name=getform value=\"POST\">");
responseContent.append("<table border=\"0\">");
responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
responseContent
.append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> "
+ "<input type=file name=\"myfile\">");
responseContent.append("</td></tr>");
responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
responseContent.append("</table></FORM>\r\n");
responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
responseContent.append("</body>");
responseContent.append("</html>");
ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
// Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
response.headers().set(CONTENT_LENGTH, buf.readableBytes());
// Write the response.
ctx.channel().writeAndFlush(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.channel().close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
messageReceived(ctx, msg);
}
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!