返回顶部
首页 > 资讯 > 后端开发 > Python >Netty如何设置为Https访问
  • 750
分享到

Netty如何设置为Https访问

2024-04-02 19:04:59 750人浏览 薄情痞子

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

摘要

目录Netty设置为https访问SSLContextFactory处理类 Netty实现Http协议Maven依赖的包1.netty启动入口2.编写NettyHttpSe

Netty设置为Https访问

SSLContextFactory

public class SSLContextFactory {
       public static SSLContext getSslContext() throws Exception {
            char[] passArray = "zhuofansoft".toCharArray();
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            KeyStore ks = KeyStore.getInstance("JKS");
            //鍔犺浇keytool 鐢熸垚鐨勬枃浠�
            FileInputStream inputStream = new FileInputStream("D://server.keystore");
           
            ks.load(inputStream, passArray);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlGorithm());
            kmf.init(ks, passArray);
            sslContext.init(kmf.geTKEyManagers(), null, null);
            inputStream.close();
            return sslContext;
        }
}

处理类 

public class HttpsSeverHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
        	HttpRequest request = (HttpRequest) msg;
        	 LOGGER.info("access messageReceived invoke success..");
             Long startTime = System.currentTimeMillis();
             // 400
             if (!request.decoderResult().isSuccess()) {
                 sendError(ctx, HttpResponseStatus.BAD_REQUEST);
                 return;
             }
             // 405
             if (request.method() != GET) {
                 sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
                 return;
             }
             FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
             Map<String, String> parmMap = new RequestParser((FullHttpRequest) request).parse();
             //Jquery跨域携带标识符
             String callback = parmMap.get("callback");
             LOGGER.info("connection JSONp header:[{}],request param:[{}]",callback,parmMap.get("requestParam"));;
             //请求参数
             DeviceRequest deviceRequest = jsONObject.parseObject(parmMap.get("requestParam"), DeviceRequest.class);
             
             DeviceResultWapper<?> result = getClientResponse(deviceRequest);
             LOGGER.info("get client response success.. response:[{}]",JSONObject.toJSONString(result));
             LOGGER.info("get client response take time:[{}]",(System.currentTimeMillis()-startTime)/1000+"s");
             String content = callback + "("+JSONObject.toJSONString(result)+")";
             byte[] bs = content.getBytes("UTF-8");
             response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
             response.headers().set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(bs.length));
             response.content().writeBytes(ByteBuffer.wrap(bs));
             ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
    }
    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
                Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private DeviceResultWapper<?> getClientResponse(DeviceRequest deviceRequest) {
        // 拼接参数
        DeviceCommandVo deviceCommandVo = DeviceType.wapperRequestParam(deviceRequest);
        if (deviceCommandVo == null) {
            return DeviceResultWapper.fail(400, "remote user with illegal param");
        }
        SerialPortOrder serialPortOrder = DeviceOrderFactory.produce(deviceCommandVo.getDeviceTypeId());
        return serialPortOrder.order(deviceCommandVo);
    }
}

Netty实现Http协议

这里简单介绍下,项目中使用netty在main方法中启动项目,实现http协议。

maven依赖的包

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.27.Final</version>
</dependency>

1.netty启动入口

package com.fotile.cloud.ruleengin;
 
import javax.servlet.ServletException;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.WEB.MockServletConfig;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
 
import com.fotile.cloud.ruleengin.falsework.NettyHttpServer;
 

public class RuleApplication
{
 
    // 引擎端口
    private final static int ENGINE_PORT = 8086;
 
    
 
    public static void main(String[] args)
    {
	// 加载spring配置
	ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
	DispatcherServlet servlet = getDispatcherServlet(ctx);
	NettyHttpServer server = new NettyHttpServer(ENGINE_PORT, servlet);
	server.start();
 
    }
 
    public static DispatcherServlet getDispatcherServlet(ApplicationContext ctx)
    {
 
	XmlWebApplicationContext mvcContext = new XmlWebApplicationContext();
	// 加载spring-mvc配置
	mvcContext.setConfigLocation("classpath:spring-mvc.xml");
	mvcContext.setParent(ctx);
	MockServletConfig servletConfig = new MockServletConfig(mvcContext.getServletContext(), "dispatcherServlet");
	DispatcherServlet dispatcherServlet = new DispatcherServlet(mvcContext);
	try
	{
	    dispatcherServlet.init(servletConfig);
	} catch (ServletException e)
	{
	    e.printStackTrace();
	}
	return dispatcherServlet;
    }
}

2.编写NettyHttpServer

package com.fotile.cloud.openplatfORM.falsework;
 
import org.apache.log4j.Logger;
import org.springframework.web.servlet.DispatcherServlet;
 
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.NIO.NioEventLoopGroup;
import io.netty.channel.Socket.nio.NiOServerSocketChannel;
 
public class NettyHttpServer implements Runnable
{
 
    private Logger LOGGER = Logger.getLogger(this.getClass());
 
    private int port;
    private DispatcherServlet servlet;
 
    public NettyHttpServer(Integer port)
    {
	this.port = port;
    }
 
    public NettyHttpServer(Integer port, DispatcherServlet servlet)
    {
	this.port = port;
	this.servlet = servlet;
    }
 
    public void start()
    {
	EventLoopGroup bossGroup = new NioEventLoopGroup();
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	try
	{
	    ServerBootstrap b = new ServerBootstrap();
	    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
		    .childHandler(new HttpServerInitializer(servlet)).option(ChannelOption.SO_BACKLOG, 128)
		    .childOption(ChannelOption.SO_KEEPALIVE, true);
 
	    LOGGER.info("NettyHttpServer Run successfully");
	    // 绑定端口,开始接收进来的连接
	    ChannelFuture f = b.bind(port).sync();
	    // 等待服务器 socket 关闭 。在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。
	    f.channel().closeFuture().sync();
	} catch (Exception e)
	{
	    System.out.println("NettySever start fail" + e);
	} finally
	{
	    workerGroup.shutdownGracefully();
	    bossGroup.shutdownGracefully();
	}
    }
 
    @Override
    public void run()
    {
	start();
    }
}

3.处理http请求、处理、返回

package com.fotile.cloud.ruleengin.falsework;
 
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
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.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.CharsetUtil;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
 
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest>
{
 
    private DispatcherServlet servlet;
 
    public HttpRequestHandler(DispatcherServlet servlet)
    {
	this.servlet = servlet;
    }
 
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception
    {
	boolean flag = HttpMethod.POST.equals(fullHttpRequest.method())
		|| HttpMethod.GET.equals(fullHttpRequest.method()) || HttpMethod.DELETE.equals(fullHttpRequest.method())
		|| HttpMethod.PUT.equals(fullHttpRequest.method());
 
	Map<String, String> parammap = getRequestParams(ctx, fullHttpRequest);
	if (flag && ctx.channel().isActive())
	{
	    // HTTP请求、GET/POST
	    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
	    MockHttpServletRequest servletRequest = new MockHttpServletRequest(
		    servlet.getServletConfig().getServletContext());
	    // headers
	    for (String name : fullHttpRequest.headers().names())
	    {
		for (String value : fullHttpRequest.headers().getAll(name))
		{
		    servletRequest.addHeader(name, value);
		}
	    }
	    String uri = fullHttpRequest.uri();
	    uri = new String(uri.getBytes("ISO8859-1"), "UTF-8");
	    uri = URLDecoder.decode(uri, "UTF-8");
	    UriComponents uriComponents = UriComponentsBuilder.fromUriString(uri).build();
	    String path = uriComponents.getPath();
	    path = URLDecoder.decode(path, "UTF-8");
	    servletRequest.setRequestURI(path);
	    servletRequest.setServletPath(path);
	    servletRequest.setMethod(fullHttpRequest.method().name());
 
	    if (uriComponents.getScheme() != null)
	    {
		servletRequest.setScheme(uriComponents.getScheme());
	    }
	    if (uriComponents.getHost() != null)
	    {
		servletRequest.setServerName(uriComponents.getHost());
	    }
	    if (uriComponents.getPort() != -1)
	    {
		servletRequest.setServerPort(uriComponents.getPort());
	    }
 
	    ByteBuf content = fullHttpRequest.content();
	    content.readerIndex(0);
	    byte[] data = new byte[content.readableBytes()];
	    content.readBytes(data);
	    servletRequest.setContent(data);
 
	    if (uriComponents.getQuery() != null)
	    {
		String query = UriUtils.decode(uriComponents.getQuery(), "UTF-8");
		servletRequest.setQueryString(query);
	    }
	    if (parammap != null && parammap.size() > 0)
	    {
		for (String key : parammap.keySet())
		{
		    servletRequest.addParameter(UriUtils.decode(key, "UTF-8"),
			    UriUtils.decode(parammap.get(key) == null ? "" : parammap.get(key), "UTF-8"));
		}
	    }
	    servlet.service(servletRequest, servletResponse);
 
	    HttpResponseStatus status = HttpResponseStatus.valueOf(servletResponse.getStatus());
	    String result = servletResponse.getContentAsString();
	    result = StringUtils.isEmpty(result) ? status.toString() : result;
	    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
		    Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));
	    response.headers().set("Content-Type", "text/json;charset=UTF-8");
	    response.headers().set("Access-Control-Allow-Origin", "*");
	    response.headers().set("Access-Control-Allow-Headers",
		    "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-File-Name");
	    response.headers().set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	    response.headers().set("Content-Length", Integer.valueOf(response.content().readableBytes()));
	    response.headers().set("Connection", "keep-alive");
	    ChannelFuture writeFuture = ctx.writeAndFlush(response);
	    writeFuture.addListener(ChannelFutureListener.CLOSE);
	}
    }
 
    
    private Map<String, String> getRequestParams(ChannelHandlerContext ctx, HttpRequest req)
    {
	Map<String, String> requestParams = new HashMap<String, String>();
	// 处理get请求
	if (req.method() == HttpMethod.GET)
	{
	    QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
	    Map<String, List<String>> parame = decoder.parameters();
	    Iterator<Entry<String, List<String>>> iterator = parame.entrySet().iterator();
	    while (iterator.hasNext())
	    {
		Entry<String, List<String>> next = iterator.next();
		requestParams.put(next.getKey(), next.getValue().get(0));
	    }
	}
	// 处理POST请求
	if (req.method() == HttpMethod.POST)
	{
	    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);
	    List<InterfaceHttpData> postData = decoder.getBodyHttpDatas(); //
	    for (InterfaceHttpData data : postData)
	    {
		if (data.getHttpDataType() == HttpDataType.Attribute)
		{
		    MemoryAttribute attribute = (MemoryAttribute) data;
		    requestParams.put(attribute.getName(), attribute.getValue());
		}
	    }
	}
	return requestParams;
    } 
}

启来后,使用postman,调用本地接口。

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

--结束END--

本文标题: Netty如何设置为Https访问

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

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

猜你喜欢
  • Netty如何设置为Https访问
    目录Netty设置为Https访问SSLContextFactory处理类 Netty实现Http协议maven依赖的包1.netty启动入口2.编写NettyHttpSe...
    99+
    2024-04-02
  • php如何访问https
    在php中使用curl库访问https,具体方法如下:function curlPost($url, $data = array(), $timeout = 30, $CA = true){ $cacert = getcwd() . '/c...
    99+
    2024-04-02
  • 群晖-第2章-设置HTTPS访问
    群晖-第2章-设置HTTPS访问 本章介绍如何通过HTTPS访问群晖,前置要求是完成群晖-第1章-IPV6的DDNS中的内容,可以是IPV4也可以是IPV6,或者你有公网IP,直接添加DNS解析也可以。只要能通过域名访问到nas就行。 本文...
    99+
    2023-10-07
    https 服务器 ssl
  • tomcat 8.5.51如何配置http及https访问
    小编给大家分享一下tomcat 8.5.51如何配置http及https访问,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!因为近期漏洞安全问题,特此用了tomca...
    99+
    2023-06-04
  • java中如何访问https
    使用java访问https,具体方法如下:URL reqURL = new URL("https://www.baidu.com" ); //创建URL对象HttpsURLConnection httpsConn = (HttpsURLCo...
    99+
    2024-04-02
  • 为什么无法访问https
    无法访问https站点的原因有以下几点SSL证书有误无法访问https网站,可能是SSL证书出现了问题,重新安装SSL证书即可。网站不可信网站不可信,导致被浏览器拦截,进入浏览器Internet选项,将网站设置为可信任网站即可。浏览器设置有...
    99+
    2024-04-02
  • javaweb如何通过https访问
    在javaweb中实现https访问的方法首先,在javaweb中获取获取SSL证书;获取到SSL证书后,在Tomcat中使用记事本打开server.xml文件;server.xml文件打开后,在文件中进行以下配置;#将port为80标签的...
    99+
    2024-04-02
  • iis如何默认访问https
    在iis中设置默认访问https的方法首先,在计算机中使用组合键“win+R”运行“Inetmgr”,打开iis管理器;进入到iis管理器页面后,在页面中选择对应的站点;在站点右侧菜单栏中,选择“URL重写”模块,并双击打开,添加规则;最后...
    99+
    2024-04-02
  • java如何实现https访问
    利用java实现https访问,具体方法如下:String result = "";URL url = new URL("网址");HttpsURLConnection conn = (HttpsURLConnection)url.open...
    99+
    2024-04-02
  • IIS中设置HTTP访问重定向到HTTPS
    目录添加规则添加入站空白规则规则详情配置完成后“应用”到当前站点URL重写配置结果 验证参考文章:不啰嗦,我们直接开始! 1、购买SSL证书(我用的...
    99+
    2024-04-02
  • Tomcat10配置端口号为443(使用https访问)
    目录前言前期准备具体操作步骤HTTP 自动跳转 HTTPS 的安全配置(可选)如何检验配置是否成功结语前言 tomcat配置好了以后默认是使用8080端口访问的,也就是需要在使用&q...
    99+
    2024-04-02
  • 如何提升https访问速度
    提升https访问速度的方法有以下几种使用TFO协议TFO协议的思路就是在一个RTT的时间内将应用层的数据跟syn包同时发送出去,从而实现节省请求次数,提升访问速度。复用session复用session不需要进行非对称密钥交换的计算,可以减...
    99+
    2024-04-02
  • phpstudy如何设置https
    在phpstudy中设置https的方法首先,在计算机中打开phpstudy,进入phpstudy操作端;进入到phpstudy操作端后,在页面中点击“网站”选项;在弹出的网站列表中,选择需要设置https的网站,点击管理,并在下拉中选择“...
    99+
    2024-04-02
  • jumpserver堡垒机配置https访问
    官方文档:https://docs.jumpserver.org/zh/master/ Jumpserver部署关闭防火墙开放策略 按照需要开放端口即可 firewall-cmd --permanent --add-port=22/tcp...
    99+
    2023-09-15
    https 网络 服务器 jumpserver 堡垒机
  • https网站如何访问http网站
    由于谷歌浏览器的安全策略更新后,https网站无法直接下载http网站的文件。解决思路有以下几种情况:1.两个网站都同时改为http或https。2.通过nginx转发。3.通过后端java代码获取对方网站的文件流然后把流返回给前端。 本文...
    99+
    2023-09-10
    服务器 运维 https
  • Nginx配置HTTPS访问(SLL证书配置)
    一、购买证书 1.登录阿里云账号,进入控制台,找到SSL证书服务 2.点击免费证书 2.1.立即购买 选择数量20,每个账户每年有20个免费证书。同意协议后点击立即购买。 2.2.创建证书并且申请  2.3.申请证书 2.4.认证...
    99+
    2023-09-01
    服务器 阿里云 ssl nginx php
  • 网站为什么要启用HTTPS访问
    本篇文章给大家分享的是有关网站为什么要启用HTTPS访问,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。 关于http和https,很多人不太了解两者有什么区别,HTT...
    99+
    2023-06-07
  • php如何设置访问端口
    本文操作环境:windows10系统、php 7、thinkpad t480电脑。设置访问端口的具体步骤如下所示:首先使用编辑工具打开 \apache\conf\httpd.conf 文件;然后在文件中找到如下配置:# Change thi...
    99+
    2015-03-03
    php 端口
  • mysql如何设置远程访问
    这篇“mysql如何设置远程访问”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“mysql如...
    99+
    2023-04-21
    mysql
  • 如何为AmazonAurora设置访问控制和权限管理
    要为Amazon Aurora设置访问控制和权限管理,可以按照以下步骤进行操作: 创建数据库用户:首先,您需要创建数据库用户,并为...
    99+
    2024-04-09
    AmazonAurora
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作