参考 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请求及响应的更多相关文章

  1. Django底层剖析之一次请求到响应的整个流程

    As we all know,所有的Web应用,其本质上其实就是一个socket服务端,而用户的浏览器就是一个socket客户端. #!/usr/bin/env python #coding:utf- ...

  2. http协议(二)请求和响应报文的构成

    http协议用于客户端和服务器之间的通信,请求访问资源的一方称为客户端,而提供资源响应的一方称为服务器端. 下面就是客户端和服务端之间简单的通信过程 PS:请求必须从客户端建立通信,服务端没收到请求之 ...

  3. iOS开发——网络篇——HTTP/NSURLConnection(请求、响应)、http响应状态码大全

    一.网络基础 1.基本概念> 为什么要学习网络编程在移动互联网时代,移动应用的特征有几乎所有应用都需要用到网络,比如QQ.微博.网易新闻.优酷.百度地图只有通过网络跟外界进行数据交互.数据更新, ...

  4. 浏览器-Tomcat服务器-请求与响应

    浏览器访问服务器,本质就是请求资源. 比如请求静态资源:index.html,我们在浏览器地址栏输入:www.a.com/index.html,浏览器为了支持HTTP协议,发送的数据必须符合HTTP协 ...

  5. AngularJS 用 Interceptors 来统一处理 HTTP 请求和响应

    Web 开发中,除了数据操作之外,最频繁的就是发起和处理各种 HTTP 请求了,加上 HTTP 请求又是异步的,如果在每个请求中来单独捕获各种常规错误,处理各类自定义错误,那将会有大量的功能类似的代码 ...

  6. http请求返回响应码的意思

    HTTP 状态响应码 意思详解/大全 HTTP状态码(HTTP Status Code)是用以表示网页服务器HTTP响应状态的3位数字代码.它由 RFC 2616 规范定义的,并得到RFC 2518. ...

  7. http请求头响应头大全

    转:http://www.jb51.net/article/51951.htm 本文为多篇“HTTP请求头相关文章”及<HTTP权威指南>一书的阅读后个人汇总整理版,以便于理解. 通常HT ...

  8. J2EE请求和响应—Servlet

    一.什么是Servlet? Servlet是执行Webserver上的一个特殊Java类.其特殊用途是响应client请求并做出处理.使得client与server端进行交互. 二.生命周期  Ser ...

  9. 老李分享:HTTP协议之请求和响应

    老李分享:HTTP协议之请求和响应   HTTP请求头详解: GET http://www.foo.com/ HTTP/1.1 GET是请求方式,请求方式有GET/POST http://www.fo ...

随机推荐

  1. Android Studio 更新gradle插件

    今天更新了CentOS, 更新了java版本. 然后gradle跪了..... 不吐槽java版本的兼容性问题了.... 反正有他自己的理由.... 那么就更新gradle咯.... 下面是方法... ...

  2. js in

    定义: in操作符用来判断某个属性属于某个对象,可以是对象的直接属性,也可以是通过prototype继承的属性.(参见hasOwnProperty) 注意事项: n         对于一般的对象属性 ...

  3. Python异常处理try...except...finally raise assert

    异常处理:try ...except  try代码块放置容易发生异常的语句:except代码块放置处理异常的语句try ...except...finally finally代码快是任何时候都会执行的 ...

  4. FreeRtos——空闲任务与空闲任务钩子函数

    以下基础知识转载自正点原子PDF资料. 前面例子 中创建的任务大部份时间都处于阻塞态.这种状态下所有的任务都不可运行,所以也不能被调度器选中.但处理器总是需要代码来执行——所以至少要有一个任务处于运行 ...

  5. RP2836 板卡信息标识

    RP2836 板卡信息标识 可以标识16种扩展应用 MCI_DA4 PD5     R120上拉 R121下拉 MCI_DA5  PD6 R125上拉 R124下拉 MCI_DA6  PD7 R122 ...

  6. Javascript代码执行过程-《悟透Javascript》笔记

    本文摘录自李战老师<悟透Javascript>一书的部分章节,为适应博客发表作了一点点修改. 1) 预编译分析. JavaScript执行引擎将所有定义式函数直接创建为作用域上的函数变量, ...

  7. 【转】【iOS测试系列】常用测试小插件的使用

    背景介绍 由于iOS系统的限制,在非越狱的自动化测试中无法实现一些常用的功能,比如不同应用之间来回切换.模拟全局的点击事件等等.但是在越狱的环境下,这些限制就不存在了,我们可以利用各种小插件来实现我们 ...

  8. 【BZOJ】3398: [Usaco2009 Feb]Bullcow 牡牛和牝牛(排列组合+乘法逆元+欧拉定理/费马小定理)

    http://www.lydsy.com/JudgeOnline/problem.php?id=3398 以下牡牛为a,牝牛为b. 学完排列计数后试着来写这题,“至少”一词可以给我们提示,我们可以枚举 ...

  9. redis是如何存储对象和集合的

    在项目中,缓存以及mq消息队列可以说是不可或缺的2个重要技术.前者主要是为了减轻数据库压力,大幅度提升性能.后者主要是为了提高用户的体验度,我理解的是再后端做的一个ajax请求(异步),并且像ribb ...

  10. Machine Learning With Spark学习笔记(在10万电影数据上训练、使用推荐模型)

    我们如今開始训练模型,还输入參数例如以下: rank:ALS中因子的个数.通常来说越大越好,可是对内存占用率有直接影响,通常rank在10到200之间. iterations:迭代次数,每次迭代都会降 ...