iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >关于Netty--Http请求处理方式
  • 594
分享到

关于Netty--Http请求处理方式

2024-04-02 19:04:59 594人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录Netty--Http请求处理业务处理逻辑Netty处理简单Http请求的例子废话不多说 上代码Netty--Http请求处理 1.这几天在看Netty权威指南,代码敲了一下,就

Netty--Http请求处理

1.这几天在看Netty权威指南,代码敲了一下,就当做个笔记吧。


public class httpserver {
	public void run(String url,Integer port) {
		EventLoopGroup bossGroup = new NIOEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup);
		bootstrap.channel(NiOServerSocketChannel.class);
		bootstrap.childHandler(new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
				ch.pipeline().addLast("http-aggregator",
						new HttpObjectAggregator(65536));
				ch.pipeline()
						.addLast("http-encoder", new HttpResponseEncoder());
				ch.pipeline()
						.addLast("http-chunked", new ChunkedWriteHandler());
				ch.pipeline().addLast("http-handler", new HttpServerHandler());
			}
		});
		try {
			ChannelFuture channelFuture = bootstrap.bind(url, port).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new HttpServer().run("127.0.0.1",8001);
	}
}

业务处理逻辑

public class HttpServerHandler extends
		SimpleChannelInboundHandler<FullHttpRequest> {
	@Override
	protected void messageReceived(ChannelHandlerContext ctx,
			FullHttpRequest fullHttpRequest) throws Exception {
		// 构造返回数据
		JSONObject jsonRootObj = new JSONObject();
		JSONObject jsonUserInfo = new JSONObject();
		jsonUserInfo.put("id", 1);
		jsonUserInfo.put("name", "张三");
		jsonUserInfo.put("passWord", "123");
		jsonRootObj.put("userInfo", jsonUserInfo);
		// 获取传递的数据
		Map<String, Object> params = getParamsFromChannel(ctx, fullHttpRequest);
		jsonRootObj.put("params", params);
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
		response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
		StringBuilder bufRespose = new StringBuilder();
		bufRespose.append(jsonRootObj.toJSONString());
		ByteBuf buffer = Unpooled.copiedBuffer(bufRespose, CharsetUtil.UTF_8);
		response.content().writeBytes(buffer);
		buffer.release();
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}
	
	private static Map<String, Object> getParamsFromChannel(
			ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest)
			throws UnsupportedEncodingException {
		HttpHeaders headers = fullHttpRequest.headers();
		String strContentType = headers.get("Content-Type").trim();
		System.out.println("ContentType:" + strContentType);
		Map<String, Object> mapReturnData = new HashMap<String, Object>();
		if (fullHttpRequest.getMethod() == HttpMethod.GET) {
			// 处理get请求
			QueryStringDecoder decoder = new QueryStringDecoder(
					fullHttpRequest.getUri());
			Map<String, List<String>> parame = decoder.parameters();
			for (Entry<String, List<String>> entry : parame.entrySet()) {
				mapReturnData.put(entry.geTKEy(), entry.getValue().get(0));
			}
			System.out.println("GET方式:" + parame.toString());
		} else if (fullHttpRequest.getMethod() == HttpMethod.POST) {
			// 处理POST请求
			if (strContentType.contains("x-www-fORM-urlencoded")) {
				HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
						new DefaultHttpDataFactory(false), fullHttpRequest);
				List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();
				for (InterfaceHttpData data : postData) {
					if (data.getHttpDataType() == HttpDataType.Attribute) {
						MemoryAttribute attribute = (MemoryAttribute) data;
						mapReturnData.put(attribute.getName(),
								attribute.getValue());
					}
				}
			} else if (strContentType.contains("application/json")) {
				// 解析json数据
				ByteBuf content = fullHttpRequest.content();
				byte[] reqContent = new byte[content.readableBytes()];
				content.readBytes(reqContent);
				String strContent = new String(reqContent, "UTF-8");
				System.out.println("接收到的消息" + strContent);
				JSONObject jsonParamRoot = JSONObject.parseObject(strContent);
				for (String key : jsonParamRoot.keySet()) {
					mapReturnData.put(key, jsonParamRoot.get(key));
				}
			} else {
				FullHttpResponse response = new DefaultFullHttpResponse(
						HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
				ctx.writeAndFlush(response).addListener(
						ChannelFutureListener.CLOSE);
			}
			System.out.println("POST方式:" + mapReturnData.toString());
		}
		return mapReturnData;
	}
}

支持Get和PostContentType为application/json、x-www-form-urlencoded的处理。

用Postman亲测无问题。

Netty处理简单Http请求的例子

废话不多说 上代码

HttpHelloWorldServerInitializer.java

import io.netty.channel.ChannelInitializer;
  import io.netty.channel.ChannelPipeline;
  import io.netty.channel.socket.SocketChannel;
  import io.netty.handler.codec.http.HttpServerCodec;
  import io.netty.handler.ssl.SslContext;
  public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
      private final SslContext sslCtx;
      public HttpHelloWorldServerInitializer(SslContext sslCtx) {
         this.sslCtx = sslCtx;
      }
      @Override
      public void initChannel(SocketChannel ch) {
          ChannelPipeline p = ch.pipeline();
          if (sslCtx != null) {
              p.addLast(sslCtx.newHandler(ch.alloc()));
          }
          p.addLast(new HttpServerCodec());
          p.addLast(new HttpHelloWorldServerHandler());
      }
  }

HttpHelloWorldServerHandler.java

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;
  public class HttpHelloWorldServerHandler extends ChannelHandlerAdapter {
      private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
      @Override
      public void channelReadComplete(ChannelHandlerContext ctx) {
          ctx.flush();
      }
      @Override
      public void channelRead(ChannelHandlerContext ctx, Object msg) {
          if (msg instanceof HttpRequest) {
              HttpRequest req = (HttpRequest) msg;
              if (HttpHeaderUtil.is100ContinueExpected(req)) {
                  ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
              }
              boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);
              FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
              response.headers().set(CONTENT_TYPE, "text/plain");
              response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
              if (!keepAlive) {
                  ctx.write(response).addListener(ChannelFutureListener.CLOSE);
              } else {
                  response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                  ctx.write(response);
              }
          }
      }
      @Override
      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
          cause.printStackTrace();
          ctx.close();
      }
  }

HttpHelloWorldServer.java

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;

public final class HttpHelloWorldServer {
      static final boolean SSL = System.getProperty("ssl") != null;
      static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
      public static void main(String[] args) throws Exception {
          // Configure SSL.
          final SslContext sslCtx;
          if (SSL) {
              SelfSignedCertificate ssc = new SelfSignedCertificate();
              sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
          } else {
              sslCtx = null;
          }
          // Configure the server.
          EventLoopGroup bossGroup = new NioEventLoopGroup(1);
          EventLoopGroup workerGroup = new NioEventLoopGroup();
          try {
              ServerBootstrap b = new ServerBootstrap();
              b.option(ChannelOption.SO_BACKLOG, 1024);
              b.group(bossGroup, workerGroup)
               .channel(NioServerSocketChannel.class)
               .handler(new LoggingHandler(LogLevel.INFO))
               .childHandler(new HttpHelloWorldServerInitializer(sslCtx));
              Channel ch = b.bind(PORT).sync().channel();
              System.err.println("Open your WEB browser and navigate to " +
                      (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
              ch.closeFuture().sync();
          } finally {
              bossGroup.shutdownGracefully();
              workerGroup.shutdownGracefully();
          }
      }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: 关于Netty--Http请求处理方式

本文链接: https://www.lsjlt.com/news/150588.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 关于Netty--Http请求处理方式
    目录Netty--Http请求处理业务处理逻辑Netty处理简单Http请求的例子废话不多说 上代码Netty--Http请求处理 1.这几天在看Netty权威指南,代码敲了一下,就...
    99+
    2024-04-02
  • vue3-HTTP请求方式
    目录vue3-HTTP请求jsonp原理 结合node.jsGet Post请求vue3-HTTP请求发出后,判断哪里出问题了在请求后添加vue3-HTTP请求 jsonp原理 结合...
    99+
    2024-04-02
  • python的HTTP请求方式(sock
    关于python的HTTP请求方式HTTP请求步骤为:       1. 域名解析2. 发起TCP的3次握手3. 建立TCP连接后发起http请求4. 服务器端响应http请求,浏览器得到html代码5. 浏览器解析html代码,并请求h...
    99+
    2023-01-31
    方式 python HTTP
  • 通过通道处理 HTTP 请求的模式
    从现在开始,我们要努力学习啦!今天我给大家带来《通过通道处理 HTTP 请求的模式》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎...
    99+
    2024-04-05
  • Ngnix如何处理http请求
    这篇文章主要为大家展示了“Ngnix如何处理http请求”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Ngnix如何处理http请求”这篇文章吧。nginx处理http的请求是nginx最重要的...
    99+
    2023-06-27
  • gateway、webflux、reactor-netty请求日志输出方式
    目录gateway、webflux、reactor-netty请求日志输出场景思路解决方案spring-webflux、gateway、springboot-start-web问题S...
    99+
    2024-04-02
  • python 3 处理HTTP 请求的包
    httphttp: https://docs.python.org/3/library/http.htmlhttp是一个包,里面含有多个模块:http.client,http.server,http.cookies,http.cookiej...
    99+
    2023-01-31
    python HTTP
  • Go语言实现关闭http请求的方式总结
    目录写在前面方式一:设置请求变量的 Close 字段值为 true方式二:设置 Header 请求头部选项 Connection: close方式三:自定义配置的 HTTP tran...
    99+
    2023-02-26
    Go关闭http请求 Go关闭http Go http
  • netty服务端处理请求联合pipeline分析
    目录两个问题NioMessageUnsafe.read()ServerBootstrap.init(Channel channel)ChannelInitializer的继承关系Pe...
    99+
    2023-05-17
    netty服务端请求联合pipeline netty服务端处理联合请求
  • PHP中的HTTP请求与响应处理
    PHP是一门脚本语言,常用于Web开发。在Web开发中,HTTP协议是重要的组成部分。对于PHP开发者来说,了解如何发送HTTP请求和处理HTTP响应是必要的技能之一。在本文中,我们将介绍PHP中的HTTP请求和响应处理。发送HTTP请求在...
    99+
    2023-05-23
    HTTP 请求 响应
  • python处理http请求中特殊字符(
    直接看代码吧# encoding:utf-8from urllib.parse import quoteimport urllib.requestimport stringimport jsonurl = quote('http://tes...
    99+
    2023-01-31
    特殊字符 python http
  • PHP中如何处理HTTP请求错误?
    在Web开发中,HTTP请求错误是时常会碰到的问题。可能是接口请求超时、参数传递错误、网络连接不正常等等。在PHP中,我们可以通过各种方法处理这些HTTP请求错误。下面就来具体探讨一下。一、使用try…catch语句使用try…catch语...
    99+
    2023-12-09
    Http请求 PHP 错误处理
  • JAVA发送HTTP请求的方式有哪些
    这篇文章主要介绍“JAVA发送HTTP请求的方式有哪些”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“JAVA发送HTTP请求的方式有哪些”文章能帮助大家解决问题。1. HttpURLConnecti...
    99+
    2023-07-05
  • Go http请求排队处理实战示例
    目录一、http请求的顺序处理方式二、http请求的异步处理方式--排队处理工作单元队列消费者协程完整代码总结一、http请求的顺序处理方式 在高并发场景下,为了降低系统压力,都会使...
    99+
    2024-04-02
  • ASP.NET处理HTTP请求的流程是什么
    这篇文章主要介绍“ASP.NET处理HTTP请求的流程是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“ASP.NET处理HTTP请求的流程是什么”文章能帮助大家解决问题。一、ASP.NET处理管...
    99+
    2023-06-30
  • java发送http get请求的两种方式
    长话短说,废话不说一、第一种方式,通过HttpClient方式,代码如下:public static String httpGet(String url, String charset) throws HttpException, IO...
    99+
    2023-05-31
    java http get
  • JavaServlet线程中AsyncContext异步处理Http请求
    目录AsyncContextAsyncContext使用示例及测试示例测试结果AsyncContext应用场景背景AsyncContext解决生产问题AsyncContext Asy...
    99+
    2023-03-01
    Java AsyncContext异步处理 Java Servlet AsyncContext
  • @FeignClient 实现简便http请求封装方式
    目录@FeignClient实现http请求封装使用流程将http请求封装为FeignClient1.配置拦截器2.注入feignClient bean3.配置pom引用4.写fei...
    99+
    2024-04-02
  • C#通过GET/POST方式发送Http请求
    目录两者的区别:参数传输数据的大小 安全性 Get请求 Post请求 介绍http请求的两种方式,get和post方式。并用C#语言实现,如何请求url并获取返回的数据 两者的区别:...
    99+
    2024-04-02
  • gateway、webflux、reactor-netty请求日志输出的方式是什么
    本篇内容介绍了“gateway、webflux、reactor-netty请求日志输出的方式是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作