Netty 처리 HTTP GET,POST 요청

21016 단어 httpnetty
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 가 스스로 봉인 한 것 이지 표준 이 아니다.
1.http 서버 쪽 을 먼저 봅 니 다.서버 코드 는 보통 이 렇 습 니 다.
package org.nepu.httpgetpost;

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;

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();
    }
}

2.서버 쪽 handler 코드 초기 화
package org.nepu.httpgetpost;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.example.securechat.SecureChatSslContextFactory;
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 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());
    }
}

3.가장 중요 한 것 은 handler 입 니 다.http 요청 을 처리 하고 http 응답 을 되 돌려 줍 니 다.(브 라 우 저 에 응답 을 되 돌려 줍 니 다)
package org.nepu.httpgetpost;

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
"); responseContent.append("===================================\r
"); responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r
"); responseContent.append("REQUEST_URI: " + request.getUri() + "\r
\r
"); responseContent.append("\r
\r
"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r
"); } responseContent.append("\r
\r
"); // 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
"); } responseContent.append("\r
\r
"); /** * 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
"); } } responseContent.append("\r
\r
"); // 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
\r
END OF GET CONTENT\r
"); 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
"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r
"); 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
\r
END OF CONTENT CHUNK BY CHUNK\r
\r
"); } // 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
BODY Attribute: " + attribute.getHttpDataType().name() + ":" + attribute.getName() + " Error while reading value: " + e1.getMessage() + "\r
"); return; } if (value.length() > 100) { responseContent.append("\r
BODY Attribute: " + attribute.getHttpDataType().name() + ":" + attribute.getName() + " data too long\r
"); } else { responseContent.append("\r
BODY Attribute: " + attribute.getHttpDataType().name() + ":" + attribute.toString() + "\r
"); } } } 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
"); responseContent.append("</head>\r
"); 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
"); // 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
"); 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
"); 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); } }

4.실행 효과
Netty处理HTTP之GET,POST请求_第1张图片
Netty处理HTTP之GET,POST请求_第2张图片
5.문제 주의
jar 는 netty-all-4.0.36.Final.jar 와 netty-example-4.0.0.Alpha 1.errai.r1.jar 를 사용 합 니 다.

좋은 웹페이지 즐겨찾기