HTTP协议基础知识
HTTP(超文本传输协议,英文:HyperText Transfer Protocol,缩写:HTTP)是基于TCP/IP协议的应用层的协议,常用于分布式、协作式和超媒体信息系统的应用层协议。
http协议的主要特点:
(1)支持CS(客户端/服务器)模式。
(2)使用简单,指定URL并携带必要的参数即可。
(3)灵活。传输非常多类型的数据对象,通过Content-Type指定即可。
(4)无状态。
我们日常浏览器输入一个url,请求服务器就是用的http协议,url的格式如下:
http请求体的组成:
- 方法
- uri
- http版本
- 参数
请求方法:
- GET 请求获取Request-URI所标识的资源
- POST 在Request-URI所标识的资源后附加新的数据
- HEAD 请求获取由Request-URI所标识的资源的响应消息报头
- PUT 请求服务器存储一个资源,并用Request-URI作为其标识
- DELETE 请求服务器删除Request-URI所标识的资源
- TRACE 请求服务器回送收到的请求信息,主要用于测试或诊断
- CONNECT 保留将来使用
- OPTIONS 请求查询服务器的性能,或者查询与资源相关的选项和需求
响应状态码:
- 1xx Informational
- 2xx Success
- 3xx Redirection
- 4xx Client Error
- 5xx Server Error
HTTP 1 VS HTTP 2:
http 1不支持长连接,每次请求建立连接,响应后就关闭连接。HTTP2支持长连接,连接复用。
Netty的http协议栈
netty提供了对http/https协议的支持,我们可以基于netty很容易写出http应用程序。
(1)编解码
- HttpRequestEncoder 对 HTTP 请求进行编码,用于客户端出参
- HttpResponseEncoder 对 HTTP 响应进行编码,用于服务端出参
- HttpRequestDecoder 对 HTTP 请求进行解码,用于服务端入参处理
- HttpResponseDecoder 对 HTTP 响应进行解码,用于客户端对响应结果解析解析
(2)请求体FullHttpRequest和响应体FullHttpResponse
FullHttpRequest
- HttpRequest:请求头信息对象;
- HttpContent:请求正文对象,一个 FullHttpRequest 中可以包含多个 HttpContent;
- LastHttpContent:标记请求正文的结束,可能会包含请求头的尾部信息;
FullHttpResponse
- HttpResponse:响应头信息对象;
- HttpContent:响应正文对象,一个 FullHttpResponse 中可以包含多个 HttpContent;
- LastHttpContent:标记响应正文的结束,可能会包含响应头的尾部信息;
(3)HttpObjectAggregator-http消息聚合器
http的post请求包含3部分:
- request line(method、uri、protocol version)
- header
- body
HttpObjectAggregator能够把多个部分整合在一个java对象中(另外消息体比较大的时候,还可能会分成多个消息,都会被聚合成一个整体对象),方便使用。
基于Netty实现http server
整体架构设计:
核心类SimpleHttpServer:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SimpleHttpServer {
private final static String host = "127.0.0.1";
private final static Integer port = 8085;
public void start() {
log.info("SimpleHttpServer start begin ");
EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup(1);
EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap()
.group(bossEventLoopGroup, workerEventLoopGroup)
.channel(NioServerSocketChannel.class)
//开启tcp nagle算法
.childOption(ChannelOption.TCP_NODELAY, true)
//开启长连接
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel c) {
c.pipeline().addLast(new HttpRequestDecoder())
.addLast(new HttpResponseEncoder())
.addLast(new HttpObjectAggregator(512 * 1024))
.addLast(new SimpleHttpServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();
log.info("SimpleHttpServer start at port " + port);
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error("SimpleHttpServer start exception,", e);
} finally {
log.info("SimpleHttpServer shutdown bossEventLoopGroup&workerEventLoopGroup gracefully");
bossEventLoopGroup.shutdownGracefully();
workerEventLoopGroup.shutdownGracefully();
}
}
}
实际处理请求的netty handler是SimpleHttpServerHandler:
import com.alibaba.fastjson.JSON;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@Slf4j
public class SimpleHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
try {
log.info("SimpleHttpServerHandler receive fullHttpRequest=" + fullHttpRequest);
String result = doHandle(fullHttpRequest);
log.info("SimpleHttpServerHandler,result=" + result);
byte[] responseBytes = result.getBytes(StandardCharsets.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK,
Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().setInt("Content-Length", response.content().readableBytes());
boolean isKeepAlive = HttpUtil.isKeepAlive(response);
if (!isKeepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set("Connection", "keep-alive");
ctx.write(response);
}
} catch (Exception e) {
log.error("channelRead0 exception,", e);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
private String doHandle(FullHttpRequest fullHttpRequest) {
if (HttpMethod.GET == fullHttpRequest.method()) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(fullHttpRequest.uri());
Map<String, List<String>> params = queryStringDecoder.parameters();
return JSON.toJSONString(params);
} else if (HttpMethod.POST == fullHttpRequest.method()) {
return fullHttpRequest.content().toString();
}
return "";
}
}
在主线程中启动服务端:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimplehttpserverApplication {
public static void main(String[] args) {
SimpleHttpServer simpleHttpServer = new SimpleHttpServer();
simpleHttpServer.start();
SpringApplication.run(SimplehttpserverApplication.class, args);
}
}
启动成功:
利用postman工具发起http请求进行测试,这里简单测试get请求:
http://127.0.0.1:8085/?name=name1&value=v2
服务端日志也打印出了处理情况,处理正常:
19:24:59.629 [nioEventLoopGroup-3-3] INFO com.summer.simplehttpserver.SimpleHttpServerHandler - SimpleHttpServerHandler receive fullHttpRequest=HttpObjectAggregator$AggregatedFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: CompositeByteBuf(ridx: 0, widx: 0, cap: 0, components=0))
GET /?name=name1&value=v2 HTTP/1.1
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Cache-Control: no-cache
Postman-Token: 7dda7e2d-6f76-4008-8b74-c2b7d78f4b2e
Host: 127.0.0.1:8085
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
content-length: 0
19:24:59.629 [nioEventLoopGroup-3-3] INFO com.summer.simplehttpserver.SimpleHttpServerHandler - SimpleHttpServerHandler,result={"name":["name1"],"value":["v2"]}
到此这篇关于Java基于Netty实现Http server的实战的文章就介绍到这了,更多相关Java Netty实现Http server内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!