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
{}
netty4.x 实现接收http请求及响应的更多相关文章
- Django底层剖析之一次请求到响应的整个流程
As we all know,所有的Web应用,其本质上其实就是一个socket服务端,而用户的浏览器就是一个socket客户端. #!/usr/bin/env python #coding:utf- ...
- http协议(二)请求和响应报文的构成
http协议用于客户端和服务器之间的通信,请求访问资源的一方称为客户端,而提供资源响应的一方称为服务器端. 下面就是客户端和服务端之间简单的通信过程 PS:请求必须从客户端建立通信,服务端没收到请求之 ...
- iOS开发——网络篇——HTTP/NSURLConnection(请求、响应)、http响应状态码大全
一.网络基础 1.基本概念> 为什么要学习网络编程在移动互联网时代,移动应用的特征有几乎所有应用都需要用到网络,比如QQ.微博.网易新闻.优酷.百度地图只有通过网络跟外界进行数据交互.数据更新, ...
- 浏览器-Tomcat服务器-请求与响应
浏览器访问服务器,本质就是请求资源. 比如请求静态资源:index.html,我们在浏览器地址栏输入:www.a.com/index.html,浏览器为了支持HTTP协议,发送的数据必须符合HTTP协 ...
- AngularJS 用 Interceptors 来统一处理 HTTP 请求和响应
Web 开发中,除了数据操作之外,最频繁的就是发起和处理各种 HTTP 请求了,加上 HTTP 请求又是异步的,如果在每个请求中来单独捕获各种常规错误,处理各类自定义错误,那将会有大量的功能类似的代码 ...
- http请求返回响应码的意思
HTTP 状态响应码 意思详解/大全 HTTP状态码(HTTP Status Code)是用以表示网页服务器HTTP响应状态的3位数字代码.它由 RFC 2616 规范定义的,并得到RFC 2518. ...
- http请求头响应头大全
转:http://www.jb51.net/article/51951.htm 本文为多篇“HTTP请求头相关文章”及<HTTP权威指南>一书的阅读后个人汇总整理版,以便于理解. 通常HT ...
- J2EE请求和响应—Servlet
一.什么是Servlet? Servlet是执行Webserver上的一个特殊Java类.其特殊用途是响应client请求并做出处理.使得client与server端进行交互. 二.生命周期 Ser ...
- 老李分享:HTTP协议之请求和响应
老李分享:HTTP协议之请求和响应 HTTP请求头详解: GET http://www.foo.com/ HTTP/1.1 GET是请求方式,请求方式有GET/POST http://www.fo ...
随机推荐
- 【C语言】22-枚举
上一讲介绍了结构体类型,这讲就介绍C语言中的另一种数据类型---枚举类型.枚举类型在iOS中也是很常用的,用法跟Java中的枚举类似. 一.枚举的概念 枚举是C语言中的一种基本数据类型,并不是构造类型 ...
- 【已解决】vbox + ubuntu 设置 1366x768 分辨率
1. 打开VBOX(Oracle VM VirtualBox),启动Ubuntu 2. 点击"设备>安装增强功能" 3. 进入Ubuntu打开文件管理器,如下图 4. 输入r ...
- 基于jQuery仿淘宝产品图片放大镜代码
今天给大家分享一款 基于jQuery淘宝产品图片放大镜代码.这是一款基于jquery.imagezoom插件实现的jQuery放大镜.适用浏览器:IE8.360.FireFox.Chrome.Safa ...
- (译).NET4.X并行任务Task需要释放吗?
摘要:本博文解释在.NET 4.X中的Task使用完后为什么不应该调用Dispose().并且说明.NET4.5对.NET4.0的Task对象进行的部分改进:减轻Task对WaitHandle对象的依 ...
- 应用DataAdapter对象更新数据库中的数据
using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class Form1 : Form ...
- 机器学习:如何通过Python入门机器学习
我们都知道机器学习是一门综合性极强的研究课题,对数学知识要求很高.因此,对于非学术研究专业的程序员,如果希望能入门机器学习,最好的方向还是从实践触发. 我了解到Python的生态对入门机器学习很有帮助 ...
- IOS微信API异常:unrecognized selector sent to instance 0x17005c9b0'
开发IOS整合微信API的时候,在运行程序的过程中可能会在注册你的APPID的时候抛出此异常而导致程序崩溃. 异常描述 [7661:2826851] *** Terminating app due t ...
- 关于Unity中的transform组件(一)
一.transform组件用途 1.维护场景树 2.对3D物体的平移,缩放,旋转 二.场景树定义 在Hierarchy视图中显示的: 一个game_scene场景,下面有Main Camera节点,D ...
- Hive:数据仓库工具,由Facebook贡献。
Hadoop Common: 在0.20及以前的版本中,包含HDFS.MapReduce和其他项目公共内容,从0.21开始HDFS和MapReduce被分离为独立的子项目,其余内容为Hadoop Co ...
- scanner, BufferedReader, InputStreamReader 区别及特殊字符的输入
1. Scanner是一个可以使用正则表达式来分析基本类型和字符串的简单文本扫描器!也就是控制台应用程序最为常用的文本输入方式!Scanner取得输入数据的依据是空格符:如按下空格键,Tab键或者En ...