netty4.x 实现接收http请求及响应

 

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

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

D:\javaNettyAction\NettyA\src\main\java\com\test\NettyHttpServerHandler.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 Files\Java\jdk1.8.0_171\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.3.4\lib\idea_rt.jar=55169:C:\Program Files\JetBrains\IntelliJ IDEA 2017.3.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_171\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\rt.jar;D:\javaNettyAction\NettyA\target\classes;C:\Users\sas\.m2\repository\io\netty\netty-all\4.1.30.Final\netty-all-4.1.30.Final.jar;C:\Users\sas\.m2\repository\com\alibaba\fastjson\1.2.51\fastjson-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
{}

 

 

 








posted @ 2018-11-12 18:42  papering  阅读(4930)  评论(0编辑  收藏  举报