首页 > 其他分享 >Netty 作为 http client 请求https 的 get与post(二)双向ssl

Netty 作为 http client 请求https 的 get与post(二)双向ssl

时间:2023-07-17 22:48:43浏览次数:45  
标签:Netty set http get request io new import netty

Netty 作为 http client 请求https 的 get与post

package com.example.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.apache.commons.codec.Charsets;

import javax.net.ssl.KeyManagerFactory;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.security.Security;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
* https://www.cnblogs.com/silyvin/p/17561473.html
* Created by joyce on 2019/12/28.
*/
public class NettyHttpClient {

public static void main(String [] f) {
System.out.println(new NettyHttpClient().send("GET"));
System.out.println("ee");
}

public String send(String msg) {
try {
Map<String, Object> map = new ConcurrentHashMap<>();
send(map);
return (String)map.get("res");
}catch (Exception e) {
e.printStackTrace();
}
return null;
}

private void send(Map<String, Object> map) throws Exception, URISyntaxException {
final EventLoopGroup WORKER_GROUP = new NioEventLoopGroup();
try {
String algo = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if(algo == null)
algo = "SunX509";

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algo);
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("mkcert/myhost.com.p12");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(inputStream, "changeit".toCharArray());
keyManagerFactory.init(keyStore, "changeit".toCharArray());

Bootstrap bootstrap = new Bootstrap();
bootstrap.group(WORKER_GROUP);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
bootstrap.option(ChannelOption.SO_TIMEOUT, 60000);

bootstrap.handler(new ChannelInitializer<SocketChannel>() {

@Override
protected void initChannel(SocketChannel ch) throws Exception {

SslContext sslContext = SslContextBuilder.forClient()
.keyManager(keyManagerFactory)
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();

ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
ch.pipeline().addLast(new HttpResponseDecoder());
ch.pipeline().addLast(new HttpRequestEncoder());
ch.pipeline().addLast(new HttpObjectAggregator(65535));
ch.pipeline().addLast(new MainHandler(map));
}
});
ChannelFuture f = bootstrap.connect("localhost", 8080);
f.channel().closeFuture().sync();
System.out.println("end");
} catch (Exception e) {
e.printStackTrace();
} catch (Error error) {
error.printStackTrace();
} finally {
WORKER_GROUP.shutdownGracefully();
}
}

@ChannelHandler.Sharable
private static class MainHandler extends SimpleChannelInboundHandler<FullHttpResponse> {
private Map<String, Object> map;

public MainHandler(Map _map) {
this.map = _map;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("active");
HttpRequest request = null;
request = HttpCreateor.createReqGet("myhost.com:8080", new URI("/test/test"));
ctx.channel().writeAndFlush(request);
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
System.out.println("read");
if (msg instanceof HttpContent) {
HttpContent httpContent = (HttpContent) msg;
ByteBuf buf = httpContent.content();
String response = buf.toString(Charsets.UTF_8);
map.put("res", response);
ctx.close();
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.channel().close();
}

private static class HttpCreateor {
public static HttpRequest createReqGet(String server, URI uri) throws Exception{
String req = "";
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
uri.toASCIIString(), Unpooled.wrappedBuffer(req.getBytes(Charsets.UTF_8)));
// 构建HTTP请求
request.headers().set(HttpHeaders.Names.HOST, server);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
request.headers().set("accept-type", Charsets.UTF_8);
request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
// request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
// 返回
return request;
}

public static HttpRequest createReqPost(byte [] body, String server, URI uri) throws Exception{

DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
uri.toASCIIString(), Unpooled.wrappedBuffer(body));
// 构建HTTP请求
request.headers().set(HttpHeaders.Names.HOST, server);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
request.headers().set("accept-type", Charsets.UTF_8);
request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
// 返回
return request;
}
}
}
}

 

标签:Netty,set,http,get,request,io,new,import,netty
From: https://www.cnblogs.com/silyvin/p/17561473.html

相关文章

  • docker buildx http: server gave HTTP response to HTTPS client
    参考:https://github.com/docker/buildx/issues/163https://github.com/thegeeklab/drone-docker-buildx/issues/153https://github.com/moby/buildkit/blob/master/docs/buildkitd.toml.md 准备用buildx构建多平台镜像,基于Dockerfilefrom私服中的jdk在执行以下命令时,......
  • 当在js文件里引入pinia时报错:Uncaught Error: []: getActivePinia was called with no
    1、问题背景我在一个js文件里需要使用pinia去修改状态存储里的内容,但是在引入pinia的时候,比如contstore=useStore()时发现报错:getActivePiniawascalledwithnoactivePinia.说是实例在文件中使用的时候,pinia实例没有被挂载。发生错误的原因是因为我在js......
  • Java爬虫--HttpClient-Post请求
    //下面是一个demo:packagetest;importorg.apache.http.HttpEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util......
  • http、socket以及websocket的区别(websocket使用举例)
    一、http、socket、websocket介绍1、HTTP(HypertextTransferProtocol):HTTP是一种应用层协议,用于在客户端和服务器之间传输超文本数据。它是基于请求-响应模型的,通过发送HTTP请求从服务器获取数据,并通过HTTP响应返回数据给客户端。HTTP是无状态的,每个请求和响应都是独立的,不保留状......
  • Charles抓取https请求及常见问题解决
    一、背景APP测试的时候,通常都需要通过抓包工具抓取各类请求,查看接口的入参、返回值等,用于分析定位问题。常用的抓包工具有fiddler、charles等,抓取http的请求比较简单,https的请求稍显复杂。由于更喜欢charles的页面风格,本篇文章主要介绍以下两点:1、Charles如何抓取电脑端和手机端的......
  • https
    https证书和私钥替换为自己的;SSL动态库在DELPHI安装目录里面可全文搜索到。测试 ......
  • 更新项目的 NuGet 包
    首先,使用dotnetlistpackage--outdated命令可以列出所有已安装的NuGet包,并显示哪些包存在更新。这个命令可能需要一些时间来运行,但是它会给出一个类似于下面这样的结果:Thefollowingsourceswereused:https://api.nuget.org/v3/index.json\\kuforedev\shared\dev......
  • jquery target
    jQuerytarget介绍在使用jQuery进行开发时,了解如何选择和操作元素是非常重要的。jQuery提供了许多方法来选择和操作元素,其中之一就是使用目标选择器(targetselector)。目标选择器是一种用来选择具有特定属性或特定属性值的元素的方法。通过使用目标选择器,我们可以非常方便地选......
  • Scrapy框架爬取HTTP/2网站
    scrapy本身是自带支持HTTP2的爬取:https://docs.scrapy.org/en/latest/topics/settings.html?highlight=H2DownloadHandler#download-handlers-base需要把这个包安装一下#本身scrapy就是基于Twisted的,http2是一个拓展包Twisted[http2]>=17.9.0然后在settings.py中打开下载......
  • go中http设置忽略证书
    在Go中,可以通过设置http.Client的Transport属性来忽略证书验证。默认情况下,http.DefaultClient使用的是http.DefaultTransport,它对证书进行了验证。但是你可以创建一个自定义的Transport并将其用作客户端的Transport,以忽略证书验证。packagemainimport( "crypto/......