先來(lái)完成一個(gè)最簡(jiǎn)單的httprequest和httpresponse的實(shí)現(xiàn)策幼。
客戶端
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new HttpRequestEncoder());//客戶端對(duì)發(fā)送的httpRequest進(jìn)行編碼
socketChannel.pipeline().addLast(new HttpResponseDecoder());//客戶端需要對(duì)服務(wù)端返回的httpresopnse解碼
// socketChannel.pipeline().addLast(new HttpClientCodec());//HttpClientCodec()包含了上面兩種
socketChannel.pipeline().addLast(new HttpClientDealing());
}
});
Channel channel = bootstrap.connect("127.0.0.1", 8080).sync().channel();
URI uri = new URI("http://127.0.0.1:8080");
DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));//生成一個(gè)默認(rèn)的httpRequest。
httpRequest.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
httpRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, httpRequest.content().readableBytes());//可以在httpRequest.headers中設(shè)置各種需要的信息。
channel.writeAndFlush(httpRequest).sync();//發(fā)送
channel.closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
private static class HttpClientDealing extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof HttpResponse){
System.out.println(msg.toString());//打印服務(wù)器返回的httpResponse
}
if(msg instanceof HttpContent) {
System.out.println(msg.toString());
}
}
}
服務(wù)端
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// socketChannel.pipeline().addLast(new HttpServerCodec());
socketChannel.pipeline().addLast(new HttpRequestDecoder());//服務(wù)器添加httpRequest解碼
socketChannel.pipeline().addLast(new HttpResponseEncoder());//服務(wù)器添加httpResponse編碼
socketChannel.pipeline().addLast(new HttpServerDataDealing());
}
});
Channel channel = serverBootstrap.bind(8080).sync().channel();
channel.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private static class HttpServerDataDealing extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof HttpRequest)
{
System.out.println(msg.toString());//打印httpRequest
}
if(msg instanceof HttpContent)
{
System.out.println(msg.toString());
}
HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("hello client".getBytes()));//建立httpResponse
httpResponse.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
httpResponse.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 11);
ctx.writeAndFlush(httpResponse);//返回響應(yīng)的httpResponse
}
}
如果只是發(fā)送簡(jiǎn)單的http請(qǐng)求以及響應(yīng)垃沦,其實(shí)非常簡(jiǎn)單。但是為了完成功能開(kāi)發(fā)用押,一般會(huì)在http頭中加入一定的消息列表用于表示此次請(qǐng)求的一些參數(shù)
名稱 | 作用 |
---|---|
Accept | 用于制定客戶端接收哪些類型的信息 |
Accept-Charset | 用于指定客戶端接受的字符集 |
Accept-Encoding | 類似于Accept肢簿,但是它用于指定一種自然語(yǔ)言 |
Authorization | 主要用于證明客戶端有權(quán)查看某個(gè)資源。當(dāng)瀏覽器訪問(wèn)一個(gè)頁(yè)面時(shí)蜻拨,如果收到服務(wù)器的響應(yīng)代碼為401(未授權(quán))池充,可以發(fā)送一個(gè)包含Authorization請(qǐng)求報(bào)頭域的請(qǐng)求,要求服務(wù)器對(duì)其進(jìn)行認(rèn)證 |
Host | 發(fā)送請(qǐng)求時(shí)缎讼,該報(bào)頭域是必需的收夸,用于指定被請(qǐng)求的資源的Internet主機(jī)和端口號(hào),它通常是從HTTP URL中提取出來(lái)的 |
User-Agent | 允許客戶端將它的操作系統(tǒng)血崭,瀏覽器和其他屬性告訴服務(wù)器 |
Content-Length | 請(qǐng)求消息體的長(zhǎng)度 |
Content-Type | 表示后面的文檔屬于什么MIME類型卧惜。Servlet默認(rèn)為text/plain,但通常需要顯式的指定為text/html夹纫。由于經(jīng)常要設(shè)置Content-Type咽瓷,因此HttpServletResponse提供了一個(gè)專用的方法setContentType |
Connection | 連接類型 |
get方法和post方法的區(qū)別
根據(jù)名稱即可得知,這兩種方法在設(shè)計(jì)的時(shí)候get就是為了獲取資源舰讹,而post是為了發(fā)送資源
在自己機(jī)子上隨便抓了一個(gè)http的get請(qǐng)求如下:
這里包含了get請(qǐng)求協(xié)議和Cookie的信息茅姜。但是沒(méi)有body,Post包沒(méi)想到怎么抓就沒(méi)有示例了月匣。其實(shí)get和post在內(nèi)容上的區(qū)別就是post多了一個(gè)body钻洒,即在httpheaders下面還有一段內(nèi)容,用于保存http提交的信息桶错。表現(xiàn)在netty代碼上如下所示
get方法
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
HttpHeaders headers = request.headers();
headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// send request
channel.writeAndFlush(request);
post方法
HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());
// Use the PostBody encoder
HttpPostRequestEncoder bodyRequestEncoder =
new HttpPostRequestEncoder(factory, request, false); // false => not multipart
//可以給body添加文件等
bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
// it is legal to add directly header or cookie into the request until finalize
//這部分headers和get方法一樣
for (Entry<String, String> entry : headers) {
request.headers().set(entry.getKey(), entry.getValue());
}
// finalize request
request = bodyRequestEncoder.finalizeRequest();
// send request
channel.write(request);
post增加的內(nèi)容
HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
HttpPostRequestEncoder bodyRequestEncoder =
new HttpPostRequestEncoder(factory, request, false); // false => not multipart
bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
request = bodyRequestEncoder.finalizeRequest();
post方法利用HttpPostRequestEncoder編碼body信息航唆,然后加入到post消息中進(jìn)行發(fā)送。