概述
主要讲述Netty处理HTTP请求和响应和需要注意的事项
Neey作为HTTP服务器
1. 编写服务器的启动程序
/** * 服务端的启动代码,重点在HttpServerInitializer这个类中,这里指定了pipeline的处理器 */
public class HttpServer {
private int port ;
public HttpServer(int port){
this.port = port;
}
public void start() throws Exception{
ServerBootstrap bootstrap = new ServerBootstrap();
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
bootstrap.group(boss,work)
.handler(new LoggingHandler(LogLevel.DEBUG))
.channel(NioServerSocketChannel.class)
.childHandler(new HttpServerInitializer());
ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();
System.out.println(" server start up on port : " + port);
f.channel().closeFuture().sync();
}
}
2. 配置服务端的pipeline处理器
public class HttpServerInitializer extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new HttpServerCodec());// http 编解码
pipeline.addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器512*1024为接收的最大contentlength
pipeline.addLast(new HttpRequestHandler());// 请求处理器
}
}
3. 编写请求处理器的业务
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
if (is100ContinueExpected(req)) {
// 检测 100 Continue,是否同意接收将要发送过来的实体
ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.CONTINUE));
}
// 因为经过HttpServerCodec处理器的处理后消息被封装为FullHttpRequest对象
// 获取请求的uri
JsonObject json = new JsonObject();
json.put("method", req.method().name()); // 获取请求方法
json.put("uri", req.uri()); // 获取请求地址
// 创建完整的响应对象
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,Unpooled.copiedBuffer(json.toJsonString(), CharsetUtil.UTF_8));
// 设置头信息
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
// 响应写回给客户端,并在协会后断开这个连接
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
4. 启动服务器
public class Application {
public static void main(String[] args) throws Exception{
HttpServer server = new HttpServer(8081);// 8081为启动端口
server.start();
}
}
Netty作为客户端
1. 编写http客户端对象
// 客户端对象,这里处理服务的启动配置和处理器配置
public class HttpClient {
public static void start(String host,int port){
// 配置一个事件循环组和一个启动器
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new HttpClientCodec()); // http客户端编解码器
channel.pipeline().addLast(new HttpObjectAggregator(65536)); // http消息聚合器
channel.pipeline().addLast(new HttpContentDecompressor()); // 数据解压处理器
channel.pipeline().addLast(new HttpClientHandler()); // 业务逻辑处理器
}
});
// 异步等待连接上远程http服务器
ChannelFuture future = bootstrap.connect(host, port).sync();
// 等待与远程http服务器断开连接
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
group.shutdownGracefully();
}
}
public static void main(String[] args) {
start("127.0.0.1", 8081);
}
}
2. 编写业务逻辑处理器
public class HttpClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 通断被激活时我们发送请求到指定路径
URI uri = new URI("/user/get");
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri.toASCIIString());
// FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); // 有时候1.1发送的请求会报400错误
// 添加请求头,保持长连接
request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);
// 添加请求头,确定请求体的长度
request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes());
// 将请求实体写入出站处理器
ctx.writeAndFlush(request);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof FullHttpResponse){
// 收到了http服务器的响应
FullHttpResponse response = (FullHttpResponse)msg;
ByteBuf buf = response.content();
String result = buf.toString(CharsetUtil.UTF_8);
System.out.println("response -> "+ result);
}
}
}
今天的文章请求数据失败怎么解决_https与http区别「建议收藏」分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/82238.html