netty  处理http请求

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!");
}
}
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> {
boolean frontendDataSendByUri = true; @Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
System.out.println(fullHttpRequest);
System.out.println(fullHttpRequest.uri());
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";
}
if (frontendDataSendByUri) {
responseContent = sendToFlume(fullHttpRequest);
}
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;
} private String sendToFlume(FullHttpRequest fullHttpRequest) {
/*
*
Flume 1.8.0 User Guide — Apache Flume http://flume.apache.org/FlumeUserGuide.html
[{
"headers" : {
"timestamp" : "434324343",
"host" : "random_host.example.com"
},
"body" : "random_body"
},
{
"headers" : {
"namenode" : "namenode.example.com",
"datanode" : "random_datanode.example.com"
},
"body" : "really_random_body"
}]
To set the charset, the request must have content type specified as application/json; charset=UTF-8 (replace UTF-8 with UTF-16 or UTF-32 as required). One way to create an event in the format expected by this handler is to use JSONEvent provided in the Flume SDK and use Google Gson to create the JSON string using the Gson#fromJson(Object, Type) method. The type token to pass as the 2nd argument of this method for list of events can be created by: Type type = new TypeToken<List<JSONEvent>>() {}.getType();
*
*
* */
// 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;
// }
// }
System.out.println(fullHttpRequest.uri());
String s = "[{\"headers\":{\"timestamp\":\""+System.currentTimeMillis()+"\",\"host\":\"random_host.example.com\"},\"body\":\""+fullHttpRequest.uri()+"\"}]";
return s;
}
}
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> {
private boolean frontendDataSendByUri = true; @Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
System.out.println(fullHttpRequest);
System.out.println(fullHttpRequest.uri());
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";
}
if (frontendDataSendByUri) {
responseContent = sendToFlume(fullHttpRequest);
}
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;
} private String sendToFlume(FullHttpRequest fullHttpRequest) {
/*
*
Flume 1.8.0 User Guide — Apache Flume http://flume.apache.org/FlumeUserGuide.html
[{
"headers" : {
"timestamp" : "434324343",
"host" : "random_host.example.com"
},
"body" : "random_body"
},
{
"headers" : {
"namenode" : "namenode.example.com",
"datanode" : "random_datanode.example.com"
},
"body" : "really_random_body"
}]
To set the charset, the request must have content type specified as application/json; charset=UTF-8 (replace UTF-8 with UTF-16 or UTF-32 as required). One way to create an event in the format expected by this handler is to use JSONEvent provided in the Flume SDK and use Google Gson to create the JSON string using the Gson#fromJson(Object, Type) method. The type token to pass as the 2nd argument of this method for list of events can be created by: Type type = new TypeToken<List<JSONEvent>>() {}.getType();
*
*
* */
// 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;
// }
// }
System.out.println(fullHttpRequest.uri());
String s = "[{\"headers\":{\"timestamp\":\"" + System.currentTimeMillis() + "\",\"host\":\"random_host.example.com\"},\"body\":{\"uri\":\"" + fullHttpRequest.uri() + "\",\"headers\":\"" + fullHttpRequest.headers() + "\"}}]";
return s;
}
} http://localhost:8080/?rtrt=34 [
    {
        "headers":{
            "timestamp":"1542092121350",
            "host":"random_host.example.com"
        },
        "body":{
            "uri":"/?rtrt=34",
            "headers":"DefaultHttpHeaders[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]"
        }
    }
]

引入 netty网关,向flume提交数据的更多相关文章

  1. netty 网关 flume 提交数据 去除透明 批处理 批提交 cat head tail 结合 管道显示行号

    D:\javaNettyAction\NettyA\src\main\java\com\test\HexDumpProxy.java package com.test; import io.netty ...

  2. HTTP content-type及POST提交数据方式

    Content-Type(内容类型),一般指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式.什么编码读取这个文件,这也是一些网页点击的结果却是一个文件 ...

  3. JQuery按回车提交数据

    引入JQuery文件 <script src="JS/jquery-1.9.1.js" type="text/javascript"></sc ...

  4. node学习笔记(二)(ajax方式向node后台提交数据)

    通过ajax向node后台提交数据过程(附手写前后台代码),并总结post与get的区别 POST 前台代码 //CSS简单给点样式 <style> form{ width: 200px; ...

  5. jQuery选取所有复选框被选中的值并用Ajax异步提交数据

    昨天和朋友做一个后台管理系统项目的时候涉及到复选框批量操作,如果用submit表单提交挺方便的,但是要实现用jQuery结合Ajax异步提交数据就有点麻烦了,因为我之前做过的项目中基本上没用Ajax来 ...

  6. pos提交提交数据时碰到Django csrf

    我的github(PS:希望star):https://github.com/thWinterSun/v-admin 最近在用Vue写前端代码,再用vue-resource向后台提交数据.项目后台是用 ...

  7. thinkPHP5.0使用form表单提交数据和删除文章,不用TP的提示页面,使用弹出提示信息

    form表单提交数据和删除文章时,TP的默认信息提示页面的看起来不是很好看,想要实现弹窗提示怎么做呢? 前端:可以使用前端的一个知识--iframe,iframe元素会创建包含另外一个文档的内联框架: ...

  8. AJAX请求提交数据

    1,AJAX准备知识:JSON JSON指的是JavaScript对象表示方法(JavaScript Object Notation) JSON是轻量级的文本数据交换格式 JSON独立于语言 JSON ...

  9. jquery ajax提交数据给后端

    大家好,今天铁柱兄给大家带一段jquery ajax提交数据给后端的教学. 初学javaweb的同学前端提交数据基本上都是用form表单提交,这玩意儿反正我是觉得不太好玩.而JavaScript aj ...

随机推荐

  1. ruby gem tips(转)

    淘宝源: https://ruby.taobao.org 升级ruby gem gem update --system 查看gem版本 gem -v 查看gem版本,gems安装目录,remote s ...

  2. QT 中设置按钮图片和文字的两种方法

    1.使用QpushButton自带的API实现: void setIcon(const QIcon &icon) void setText(const QString &text) 该 ...

  3. [转]__cdecl与__stdcall

    来自Programming Windows 5th Edition The WinMain function is given a type of WINAPI (as is every Window ...

  4. oozie常见错误问题

    1.  Error: HTTP error code: 404 : Not Found 原因: 在环境变量中配置的OOZIE_URL有问题配置成了 export OOZIE_URL=http://dw ...

  5. 个别图片IE中无法显示问题

    今天有人保障,某些图片在IE下无法打开,但是其他浏览器均没有问题.以前还真没遇到过这类问题,从上至下查看了一遍,能排除的因素基本都排除了,还是不知道为什么不能显示,真是奇怪了.最后注意到无法显示的图片 ...

  6. ssdfd

    http://www.phpweb.net/ http://wenku.baidu.com/view/6044c67c27284b73f242506b.htmlhttp://www.jb51.net/ ...

  7. 一个通用的JavaScript分页

    1.JavaScript代码 Pagination=function(id) { var totalNum=0; var maxNum=10; var pageUrl=""; va ...

  8. C++ 类中的const关键字

    //类中的const关键字 #include<iostream> using namespace std; class Point{ public: //这个const关键字本质上修饰的是 ...

  9. MapReduce总体架构分析

    转自:http://blog.csdn.net/Androidlushangderen/article/details/41051027 继前段时间分析Redis源码一段时间之后,我即将开始接下来的一 ...

  10. Python之并行

    http://www.open-open.com/news/view/1c0179b/