java netty httpreq_Netty 作为 http client 请求https 的post

spring boot server:

package com.example.demo.controller.ssl;

import com.example.demo.controller.ProxyController;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import serial.MyBaseProto;

/**

* https://www.cnblogs.com/silyvin/p/12099743.html

* Created by joyce on 2019/11/17.

*/

@Controller

@RequestMapping("/json")

public class JsonController {

@RequestMapping(value = "/testhttps")

@ResponseBody

public String get() {

return "xxx";

}

@RequestMapping(value = "/testhttpsPost", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")

@ResponseBody

public TT post(@RequestBody TT tt) {

tt.setPa("12");

tt.setPb("22");

return tt;

}

private static class TT {

String pa;

String pb;

public String getPa() {

return pa;

}

public void setPa(String pa) {

this.pa = pa;

}

public String getPb() {

return pb;

}

public void setPb(String pb) {

this.pb = pb;

}

}

}

package com.example.demo.controller.ssl.netty;

import io.netty.bootstrap.Bootstrap;

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.HttpObjectAggregator;

import io.netty.handler.codec.http.HttpRequestEncoder;

import io.netty.handler.codec.http.HttpResponseDecoder;

import io.netty.handler.ssl.SslContext;

import io.netty.handler.ssl.SslContextBuilder;

import io.netty.handler.ssl.SslHandler;

import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import io.netty.util.ReferenceCountUtil;

import javax.net.ssl.SSLEngine;

import javax.net.ssl.SSLException;

import java.net.URISyntaxException;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.TimeoutException;

/**

* 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(new NettyHttpClient().send("POST"));

}

public String send(String msg) {

try {

Map map = new ConcurrentHashMap<>();

send(msg, map);

return (String)map.get("res");

}catch (Exception e) {

e.printStackTrace();

}

return null;

}

private void send(String msg, Map map) throws Exception, URISyntaxException {

try {

final Bootstrap b = BootStrapManager.newBootStrap();

b.handler(new ClientInit(new MainHandler(map, msg), SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()));

ChannelFuture f = b.connect("localhost", 8080);

f.channel().closeFuture().sync(); 阻塞

} catch (Exception e) {

e.printStackTrace();

} finally {

}

}

private static class ClientInit extends ChannelInitializer {

private ChannelInboundHandler handler;

private SslContext context;

public ClientInit(ChannelInboundHandler handler, SslContext context) {

this.handler = handler;

this.context = context;

}

@Override

protected void initChannel(SocketChannel ch) throws Exception {

if (true) {

ch.pipeline().addLast(context.newHandler(ch.alloc()));

}

ch.pipeline().addLast(new HttpResponseDecoder());

ch.pipeline().addLast(new HttpRequestEncoder());

ch.pipeline().addLast(new HttpObjectAggregator(65535));

ch.pipeline().addLast(handler);

}

}

private static class BootStrapManager {

private static final EventLoopGroup WORKER_GROUP = new NioEventLoopGroup();

private static Bootstrap CLIENT_BOOTSTRAP ;

public static Bootstrap getBootStrap() {

if(CLIENT_BOOTSTRAP == null) {

synchronized (BootStrapManager.class) {

if(CLIENT_BOOTSTRAP == null) {

CLIENT_BOOTSTRAP = newBootStrap();

}

}

}

return CLIENT_BOOTSTRAP;

}

public static Bootstrap newBootStrap() {

Bootstrap bootstrap = new Bootstrap();

bootstrap.group(WORKER_GROUP);

bootstrap.channel(NioSocketChannel.class);

bootstrap.option(ChannelOption.SO_KEEPALIVE, false);

bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

return bootstrap;

}

}

}

package com.example.demo.controller.ssl.netty;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandler;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;

import io.netty.handler.codec.http.*;

import java.io.IOException;

import java.net.URI;

import java.util.Map;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelFutureListener;

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandler.Sharable;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;

import io.netty.handler.codec.http.HttpObject;

import org.apache.commons.codec.Charsets;

/**

* Created by joyce on 2019/12/28.

*/

@ChannelHandler.Sharable

public class MainHandler extends SimpleChannelInboundHandler {

private Map map;

private String msg;

public MainHandler(Map _map, String msg) {

this.map = _map;

this.msg = msg;

}

@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {

System.out.println("active");

HttpRequest request = null;

if(msg.equals("GET"))

request = HttpCreateor.createReqGet("localhost", new URI("/json/testhttps"));

if(msg.equals("POST"))

request = HttpCreateor.createReqPost(

"{\"pa\":\"BeJson\",\"pb\":\"sss\"}".getBytes(), "localhost", new URI("/json/testhttpsPost"));

// 发送

ctx.channel().writeAndFlush(request).addListener(new ChannelFutureListener() {

@Override

public void operationComplete(ChannelFuture future) throws Exception {

}

});

}

@Override

protected void channelRead0(ChannelHandlerContext ctx, HttpObject 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 {

/**

* 构造HTTP请求

* @return

* @throws Exception

*/

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;

}

}

}

active

22:23:11.389 [nioEventLoopGroup-2-1] DEBUG io.netty.handler.ssl.util.InsecureTrustManagerFactory - Accepting a server certificate: CN=sun, OU=citi, O=citi, L=sh, ST=sh, C=cn

22:23:11.516 [nioEventLoopGroup-2-1] DEBUG io.netty.handler.ssl.SslHandler - [id: 0x1adda983, /127.0.0.1:63691 => localhost/127.0.0.1:8080] HANDSHAKEN: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

read

xxx

active

22:23:11.592 [nioEventLoopGroup-2-2] DEBUG io.netty.handler.ssl.util.InsecureTrustManagerFactory - Accepting a server certificate: CN=sun, OU=citi, O=citi, L=sh, ST=sh, C=cn

22:23:11.613 [nioEventLoopGroup-2-2] DEBUG io.netty.handler.ssl.SslHandler - [id: 0xbfec2d89, /127.0.0.1:63692 => localhost/127.0.0.1:8080] HANDSHAKEN: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

read

{"pa":"12","pb":"22"}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一些关于使用Netty实现WebSocket客户端(支持wss安全连接)的建议。 首先,您需要确保已经包含了Netty和WebSocket依赖项。然后可以按照以下步骤实现: 1. 创建一个WebSocketClientHandshaker,用于握手和建立WebSocket连接。这里我们需要使用wss连接,因此需要使用WebSocketClientHandshakerFactory创建一个以SSL/TLS方式连接的WebSocket连接。 2. 创建一个WebSocketClientHandler,处理WebSocket连接的事件。这里我们需要重写channelActive、channelInactive和channelRead0等方法,以便在连接建立、关闭和接收到消息时执行相应的操作。 3. 创建一个Bootstrap实例,用于启动客户端。设置bootstrap的group、channel、handler等属性。 4. 连接到WebSocket服务器。通过bootstrap的connect方法连接到指定的WebSocket服务器。 下面是一个简单的示例代码: ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import java.net.URI; import java.util.concurrent.TimeUnit; public class NettyWebSocketClient { private final URI uri; private final EventLoopGroup group; private Channel channel; public NettyWebSocketClient(URI uri) { this.uri = uri; this.group = new NioEventLoopGroup(); } public void connect() throws Exception { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build(); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, true, null); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LoggingHandler(LogLevel.DEBUG)); pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new HttpRequestEncoder()); pipeline.addLast(new HttpResponseDecoder()); pipeline.addLast(new SslHandler(sslContext.newEngine(ch.alloc(), uri.getHost(), uri.getPort()))); pipeline.addLast(new WebSocketClientProtocolHandler(handshaker)); pipeline.addLast(new WebSocketFrameAggregator(65536)); pipeline.addLast(new WebSocketClientHandler()); } }); channel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel(); handshaker.handshake(channel).sync(); } catch (Exception e) { group.shutdownGracefully(); throw e; } } public void sendMessage(WebSocketFrame frame) { channel.writeAndFlush(frame); } public void close() { channel.writeAndFlush(new CloseWebSocketFrame()) .addListener(ChannelFutureListener.CLOSE); group.shutdownGracefully(); } private class WebSocketClientHandler extends io.netty.channel.SimpleChannelInboundHandler<Object> { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected response (status=" + response.status() + ", content=" + response.content().toString() + ")"); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; // 处理文本消息 System.out.println("Received Text Message: " + textFrame.text()); } else if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame; // 处理二进制消息 } else if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PingWebSocketFrame(frame.content().retain())); } else if (frame instanceof CloseWebSocketFrame) { channel.close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("WebSocket Client disconnected!"); group.schedule(() -> { try { connect(); } catch (Exception e) { e.printStackTrace(); } }, 10, TimeUnit.SECONDS); } } } ``` 在使用时,您可以按照以下步骤: ```java URI uri = new URI("wss://your.websocket.server.com"); NettyWebSocketClient client = new NettyWebSocketClient(uri); client.connect(); // 发送消息 WebSocketFrame frame = new TextWebSocketFrame("Hello, WebSocket!"); client.sendMessage(frame); // 关闭连接 client.close(); ``` 希望这些信息能够对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值