netty与http服务

客官°小女子只卖身不卖艺 2022-06-07 05:07 259阅读 0赞

http客户端

  1. package httpClient;
  2. import org.apache.commons.httpclient.HttpClient;
  3. import org.apache.commons.httpclient.methods.PostMethod;
  4. import org.apache.commons.httpclient.methods.StringRequestEntity;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. /**
  8. * Created by sff on 2017/10/10.
  9. */
  10. public class HttpClientTest {
  11. public static void send(String url, String content) throws Exception{
  12. HttpClient httpClient = new HttpClient();
  13. httpClient.getParams().setContentCharset("UTF-8");
  14. PostMethod postMethod = new PostMethod(url);
  15. Map<String, String> headerMap = new HashMap<>();
  16. headerMap.put("Host", "****");
  17. headerMap.put("Accept-Encoding", "gzip");
  18. for (Map.Entry<String, String> entry : headerMap.entrySet()) {
  19. postMethod.addRequestHeader(entry.getKey(), entry.getValue());
  20. }
  21. StringRequestEntity entity = new StringRequestEntity(content, "text/plain", "UTF-8");
  22. postMethod.setRequestEntity(entity);
  23. try {
  24. int result = httpClient.executeMethod(postMethod);
  25. if (result == 200) {
  26. System.out.println("发送成功");
  27. } else{
  28. System.out.println("发送失败");
  29. }
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. public static void main(String[] args) throws Exception{
  35. StringBuilder stringBuilder = new StringBuilder("发送内容:\n");
  36. // for(int i = 0; i < 1000; i++){
  37. stringBuilder.append(0).append(" ");
  38. for(int j = 0; j < 1000; j++){
  39. stringBuilder.append(j);
  40. }
  41. stringBuilder.append("\n");
  42. // }
  43. send("http://127.0.0.1:8088?", stringBuilder.toString());
  44. }
  45. }

postMethod的setRequestEntity()方法是想post方法中放入参数,看requestEntity实现类有很多种

netty做http服务

netty

  1. package httpServer;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.*;
  4. import io.netty.channel.nio.NioEventLoopGroup;
  5. import io.netty.channel.socket.SocketChannel;
  6. import io.netty.channel.socket.nio.NioServerSocketChannel;
  7. import io.netty.handler.codec.http.HttpObjectAggregator;
  8. import io.netty.handler.codec.http.HttpRequestDecoder;
  9. import io.netty.handler.codec.http.HttpRequestEncoder;
  10. import io.netty.handler.codec.http.HttpServerCodec;
  11. import io.netty.handler.stream.ChunkedWriteHandler;
  12. import logbus.agent.log.LogDefinition;
  13. import logbus.agent.netty.codec.XDecoderFactory;
  14. import logbus.agent.netty.codec.XEncoderFactory;
  15. import logbus.agent.sink.Sink;
  16. import logbus.agent.source.impl.server.netty.ServerSourceHandlerFactory;
  17. import logbus.protocol.netty.XNetty;
  18. import java.util.Map;
  19. /**
  20. * http请求的netty服务器
  21. * Created by sff on 2017/10/9.
  22. */
  23. public class HttpServerSourceNetty implements XNetty {
  24. /** 端口号 */
  25. private int port;
  26. // 分配用于处理事务的线程组数量
  27. protected static final int bisGroupSize = Runtime.getRuntime().availableProcessors();
  28. // 每个线程组中线程的数量
  29. protected static final int worGroupSize = 2;
  30. /**
  31. * 初始化
  32. * @param port
  33. * @param encrypt
  34. * @throws InterruptedException
  35. */
  36. public HttpServerSourceNetty(String groupName, String sourceName, int port, boolean encrypt) throws InterruptedException{
  37. this.port = port;
  38. try{
  39. start();
  40. } catch (InterruptedException e){
  41. String msg = new StringBuilder("name值为").append(sourceName).append(
  42. "的source的server服务器开启失败").toString();
  43. LogDefinition.COMMON.error(msg, e);
  44. throw new InterruptedException(msg);
  45. }
  46. }
  47. @Override
  48. public void start() throws InterruptedException{
  49. EventLoopGroup boss = new NioEventLoopGroup(bisGroupSize);
  50. EventLoopGroup worker = new NioEventLoopGroup(worGroupSize);
  51. ServerBootstrap bootstrap = new ServerBootstrap();
  52. //group函数其实就是将parentGroup和ChildGroup进行赋值,其中parentGroup用于处理accept事件,ChildGroup用于处理accpt的Channel的IO事件。
  53. bootstrap.group(boss, worker);
  54. bootstrap.channel(NioServerSocketChannel.class);
  55. bootstrap.option(ChannelOption.SO_BACKLOG, 128);
  56. bootstrap.option(ChannelOption.TCP_NODELAY, true);
  57. bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
  58. bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
  59. @Override
  60. protected void initChannel(SocketChannel socketChannel) throws Exception{
  61. ChannelPipeline p = socketChannel.pipeline();
  62. // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
  63. p.addLast(new HttpServerCodec());
  64. p.addLast("aggregator", new HttpObjectAggregator(64 * 1024 * 1024));
  65. p.addLast("chunkedWriter", new ChunkedWriteHandler());
  66. p.addLast(new HttpServerSourceHandlerFactory().getHandler());
  67. }
  68. });
  69. ChannelFuture f = bootstrap.bind(port).sync();
  70. if(f.isSuccess()){
  71. }
  72. }
  73. }

netty处理的handler

  1. package feedback.communicate.netty.http;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.ByteBufAllocator;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.channel.ChannelInboundHandlerAdapter;
  6. import io.netty.handler.codec.http.*;
  7. import java.net.HttpCookie;
  8. import java.net.URI;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. * http server handler
  13. * Created by sff on 2018/4/20.
  14. */
  15. public class HttpServerHandler extends ChannelInboundHandlerAdapter {
  16. public HttpServerHandler(){
  17. super();
  18. }
  19. private List<String> splitMultiCookies(String header) {
  20. List<String> cookies = new java.util.ArrayList<String>();
  21. int quoteCount = 0;
  22. int p, q;
  23. for (p = 0, q = 0; p < header.length(); p++) {
  24. char c = header.charAt(p);
  25. if (c == '"') quoteCount++;
  26. if (c == ';' && (quoteCount % 2 == 0)) {
  27. // it is comma and not surrounding by double-quotes
  28. cookies.add(header.substring(q, p));
  29. q = p + 1;
  30. }
  31. }
  32. cookies.add(header.substring(q));
  33. return cookies;
  34. }
  35. /**
  36. * 接收get请求的数据
  37. * @param ctx
  38. * @param msg
  39. */
  40. public void handler(ChannelHandlerContext ctx, Object msg) throws Exception{
  41. if (msg instanceof HttpRequest) {
  42. System.out.println("###################");
  43. FullHttpRequest request = (FullHttpRequest) msg;
  44. // 收取cookie
  45. String cookieHeader = request.headers().get(HttpHeaderNames.COOKIE);
  46. List<String> cookieStrs = splitMultiCookies(cookieHeader);
  47. for(int i = 0; i < cookieStrs.size(); i++) {
  48. List<HttpCookie> list = HttpCookie.parse(cookieStrs.get(i));
  49. for (int j = 0; j < list.size(); j++) {
  50. System.out.println(list.get(j).toString());
  51. }
  52. }
  53. // if GET Method: should not try to create a HttpPostRequestDecoder
  54. if (request.method().equals(HttpMethod.GET)) {
  55. URI uri = new URI(request.uri());
  56. QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
  57. Map<String, List<String>> uriAttributes = decoderQuery.parameters();
  58. System.out.println("GET内容:" + uri.getQuery());
  59. }
  60. //判断request请求是否是post请求
  61. if (request.method().equals(HttpMethod.POST)) {
  62. ByteBuf content = request.content();
  63. byte[] req = new byte[content.readableBytes()];
  64. content.readBytes(req);
  65. String resultStr = new String(req, "UTF-8");
  66. System.out.println("POST内容:" + resultStr);
  67. content.release();
  68. } else{
  69. request.release();
  70. }
  71. // 发送消息
  72. String r = "sff is a good man.";
  73. ByteBuf bf = ByteBufAllocator.DEFAULT.buffer(8*1024);
  74. bf.writeBytes(r.getBytes());
  75. HttpHeaders httpHeaders = new DefaultHttpHeaders();
  76. HttpCookie cookie1 = new HttpCookie("feedback", "sff");
  77. cookie1.setHttpOnly(true);
  78. HttpCookie cookie2 = new HttpCookie("session_id", "123456");
  79. HttpCookie cookie3 = new HttpCookie("tenant", "STULIB");
  80. httpHeaders.add(HttpHeaderNames.SET_COOKIE, cookie1); // add 是可以添加同名的对象,set会把同名的对象覆盖掉
  81. httpHeaders.add(HttpHeaderNames.SET_COOKIE, cookie2);
  82. httpHeaders.add(HttpHeaderNames.SET_COOKIE, cookie3);
  83. httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
  84. httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, bf.readableBytes());
  85. httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  86. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, bf);
  87. response.headers().set(httpHeaders);
  88. ctx.writeAndFlush(response);
  89. }
  90. }
  91. @Override
  92. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  93. handler(ctx, msg);
  94. }
  95. @Override
  96. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  97. throws Exception {
  98. // ignore
  99. }
  100. }

FullHttpRequest的类里面可以查询header,body等数据

参考:Netty处理HTTP之GET,POST请求

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Netty剖析之Http服务案例

    前言 前面我们讲了Netty的线程模型,还有一些Netty的特性,以及使用Netty编写过一个Tcp服务案例,本次呢,我们将结合前面所学的知识,来编写一个Http服务案例