Netty 作为 http client 请求https 的 get与post(二)双向ssl
接
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;
}
}
}
}