zoukankan      html  css  js  c++  java
  • netty4.x 实现接收http请求及响应

    参考 netty4.x 实现接收http请求及响应 - En taro tassadar - CSDN博客 https://blog.csdn.net/sinat_39783636/article/details/81941476

    请改fastjson处理json;弱化为web-表单的处理;目的是依赖Netty实现网关;

    D:javaNettyActionNettyAsrcmainjavacom estNettyHttpServerHandler.java

    package com.test;

    import com.alibaba.fastjson.JSONObject;
    import io.netty.buffer.ByteBuf;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.handler.codec.http.*;
    import io.netty.handler.codec.http.multipart.*;
    import io.netty.util.CharsetUtil;

    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import static io.netty.buffer.Unpooled.copiedBuffer;

    public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
    System.out.println(fullHttpRequest);
    String responseContent;
    HttpResponseStatus responseStatus = HttpResponseStatus.OK;
    if (fullHttpRequest.method() == HttpMethod.GET) {
    System.out.println(getGetParamasFromChannel(fullHttpRequest));
    responseContent = "GET method over";
    } else if (fullHttpRequest.method() == HttpMethod.POST) {
    System.out.println(getPostParamsFromChannel(fullHttpRequest));
    responseContent = "POST method data";
    } else {
    responseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    responseContent = "INTERNAL_SERVER_ERROR";
    }
    FullHttpResponse response = responseHandler(responseStatus, responseContent);
    channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private Map<String, Object> getGetParamasFromChannel(FullHttpRequest fullHttpRequest) {
    Map<String, Object> params = new HashMap<String, Object>();
    if (fullHttpRequest.method() == HttpMethod.GET) {
    QueryStringDecoder decoder = new QueryStringDecoder(fullHttpRequest.uri());
    Map<String, List<String>> paramList = decoder.parameters();
    for (Map.Entry<String, List<String>> entry : paramList.entrySet()) {
    params.put(entry.getKey(), entry.getValue().get(0));
    }
    return params;
    } else {
    return null;
    }
    }

    private Map<String, Object> getPostParamsFromChannel(FullHttpRequest fullHttpRequest) {
    Map<String, Object> params = new HashMap<String, Object>();
    if (fullHttpRequest.method() == HttpMethod.POST) {
    String strContentType = fullHttpRequest.headers().get("Content-type").trim();
    // if (strContentType.contains("x-www-form-urlencoded")) {
    if (strContentType.contains("form")) {
    params = getFormParams(fullHttpRequest);
    } else if (strContentType.contains("application/json")) {
    try {
    params = getJSONParams(fullHttpRequest);
    } catch (UnsupportedEncodingException e) {
    return null;
    }
    } else {
    return null;
    }
    return params;
    }
    return null;
    }

    private Map<String, Object> getFormParams(FullHttpRequest fullHttpRequest) {
    Map<String, Object> params = new HashMap<String, Object>();
    // HttpPostMultipartRequestDecoder
    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpRequest);
    List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();
    for (InterfaceHttpData data : postData) {
    if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
    MemoryAttribute attribute = (MemoryAttribute) data;
    params.put(attribute.getName(), attribute.getValue());
    }
    }
    return params;
    }

    private Map<String, Object> getJSONParams(FullHttpRequest fullHttpRequest) throws UnsupportedEncodingException {
    Map<String, Object> params = new HashMap<String, Object>();
    ByteBuf content = fullHttpRequest.content();
    byte[] reqContent = new byte[content.readableBytes()];
    content.readBytes(reqContent);
    String strContent = new String(reqContent, "UTF-8");
    JSONObject jsonObject = JSONObject.parseObject(strContent);
    for (String key : jsonObject.keySet()) {
    params.put(key, jsonObject.get(key));
    }
    return params;
    }

    private FullHttpResponse responseHandler(HttpResponseStatus status, String responseContent) {
    ByteBuf content = copiedBuffer(responseContent, CharsetUtil.UTF_8);
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
    response.headers().set("Content-Type", "text/plain;charset=UTF-8;");
    response.headers().set("Content-Length", response.content().readableBytes());
    return response;
    }
    }



    package com.test;

    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.HttpObjectAggregator;
    import io.netty.handler.codec.http.HttpRequestDecoder;
    import io.netty.handler.codec.http.HttpResponseEncoder;
    import io.netty.handler.stream.ChunkedWriteHandler;

    public class NettyHttpServer {
    private int port;

    public NettyHttpServer(int port) {
    this.port = port;
    }

    public void init() throws Exception {
    EventLoopGroup parentGroup = new NioEventLoopGroup();
    EventLoopGroup childGroup = new NioEventLoopGroup();
    try {
    ServerBootstrap server = new ServerBootstrap();
    server.group(parentGroup, childGroup)
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel socketChanel) throws Exception {
    socketChanel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
    socketChanel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));
    socketChanel.pipeline().addLast("http-encoder", new HttpResponseEncoder());
    socketChanel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
    socketChanel.pipeline().addLast("http-server", new NettyHttpServerHandler());
    }
    }
    );
    ChannelFuture future = server.bind(this.port).sync();
    future.channel().closeFuture().sync();
    } finally {
    childGroup.shutdownGracefully();
    parentGroup.shutdownGracefully();
    }
    }

    public static void main(String[] args) {
    NettyHttpServer server = new NettyHttpServer(8080);
    try {
    server.init();
    } catch (Exception e) {
    e.printStackTrace();
    System.err.println("exception: " + e.getMessage());
    }
    System.out.println("server close!");
    }
    }


    "C:Program FilesJavajdk1.8.0_171injava" "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2017.3.4libidea_rt.jar=55169:C:Program FilesJetBrainsIntelliJ IDEA 2017.3.4in" -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_171jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_171jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_171jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_171jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_171jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_171jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_171jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_171jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_171jrelibext ashorn.jar;C:Program FilesJavajdk1.8.0_171jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_171jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_171jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_171jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_171jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_171jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_171jrelibjce.jar;C:Program FilesJavajdk1.8.0_171jrelibjfr.jar;C:Program FilesJavajdk1.8.0_171jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_171jrelibjsse.jar;C:Program FilesJavajdk1.8.0_171jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_171jrelibplugin.jar;C:Program FilesJavajdk1.8.0_171jrelib esources.jar;C:Program FilesJavajdk1.8.0_171jrelib t.jar;D:javaNettyActionNettyA argetclasses;C:Userssas.m2 epositoryio etty etty-all4.1.30.Final etty-all-4.1.30.Final.jar;C:Userssas.m2 epositorycomalibabafastjson1.2.51fastjson-1.2.51.jar" com.test.NettyHttpServer
    HttpObjectAggregator$AggregatedFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: CompositeByteBuf(ridx: 0, widx: 262, cap: 262, components=1))
    POST / HTTP/1.1
    Content-Type: multipart/form-data; boundary=--------------------------440083270211178529470072
    cache-control: no-cache
    Postman-Token: b69cf502-ec22-415f-836d-db275d1f20f0
    User-Agent: PostmanRuntime/7.3.0
    Accept: */*
    Host: localhost:8080
    accept-encoding: gzip, deflate
    content-length: 262
    Connection: keep-alive
    {aa=a2, de=21}
    HttpObjectAggregator$AggregatedFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: CompositeByteBuf(ridx: 0, widx: 151, cap: 151, components=1))
    POST / HTTP/1.1
    Content-Type: application/json
    cache-control: no-cache
    Postman-Token: 7340f5f0-2bdc-413a-96e5-37fb45a1b1af
    User-Agent: PostmanRuntime/7.3.0
    Accept: */*
    Host: localhost:8080
    accept-encoding: gzip, deflate
    content-length: 151
    Connection: keep-alive
    {headers={"host":"random_host.example.com","timestamp":"434324343"}, body=str86677}
    HttpObjectAggregator$AggregatedFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: CompositeByteBuf(ridx: 0, widx: 0, cap: 0, components=0))
    GET /?rtrt=34&tytyty=7 HTTP/1.1
    Host: localhost:8080
    Connection: keep-alive
    Cache-Control: max-age=0
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    Accept-Encoding: gzip, deflate, br
    Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6,cy;q=0.5
    Cookie: Pycharm-8d0b2786=568b4aae-c829-4e47-ab4b-ddc1476c8726; Idea-80a56cc9=5ec4599e-2cf3-4fc1-b0c2-3fb43cf0485d
    content-length: 0
    {rtrt=34, tytyty=7}
    HttpObjectAggregator$AggregatedFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: CompositeByteBuf(ridx: 0, widx: 0, cap: 0, components=0))
    GET /favicon.ico HTTP/1.1
    Host: localhost:8080
    Connection: keep-alive
    Pragma: no-cache
    Cache-Control: no-cache
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
    Accept: image/webp,image/apng,image/*,*/*;q=0.8
    Referer: http://localhost:8080/?rtrt=34&tytyty=7
    Accept-Encoding: gzip, deflate, br
    Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6,cy;q=0.5
    Cookie: Pycharm-8d0b2786=568b4aae-c829-4e47-ab4b-ddc1476c8726; Idea-80a56cc9=5ec4599e-2cf3-4fc1-b0c2-3fb43cf0485d
    content-length: 0
    {}








  • 相关阅读:
    627. Swap Salary
    176. Second Highest Salary
    596. Classes More Than 5 Students
    183. Customers Who Never Order
    181. Employees Earning More Than Their Managers
    182. Duplicate Emails
    175. Combine Two Tables
    620. Not Boring Movies
    595. Big Countries
    HDU 6034 Balala Power! (贪心+坑题)
  • 原文地址:https://www.cnblogs.com/rsapaper/p/9948277.html
Copyright © 2011-2022 走看看