netty4 HTTPclient 可添加参数

下了netty4的demo,但是发现给例子不能添加参数。所以自己改了一下,用netty实现http协议get请求并追加参数。

HttpSnoopClient.java
 1 import io.netty.bootstrap.Bootstrap;
 2 import io.netty.channel.Channel;
 3 import io.netty.channel.EventLoopGroup;
 4 import io.netty.channel.nio.NioEventLoopGroup;
 5 import io.netty.channel.socket.nio.NioSocketChannel;
 6 import io.netty.handler.codec.http.ClientCookieEncoder;
 7 import io.netty.handler.codec.http.DefaultCookie;
 8 import io.netty.handler.codec.http.DefaultFullHttpRequest;
 9 import io.netty.handler.codec.http.HttpHeaders;
10 import io.netty.handler.codec.http.HttpMethod;
11 import io.netty.handler.codec.http.HttpRequest;
12 import io.netty.handler.codec.http.HttpVersion;
13 import io.netty.handler.ssl.SslContext;
14 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
15 import java.net.URI;
16
17 /**
18  * A simple HTTP client that prints out the content of the HTTP response to
19  * {@link System#out} to test {@link HttpSnoopServer}.
20  */
21 public final class HttpSnoopClient {
22
23     static final String URL = System.getProperty("url", "http://www.baidu.com/s");
24     static final String PARAM = "?wd=罗龙龙";
25
26     public static void main(String[] args) throws Exception {
27         URI uri = new URI(URL);
28         String scheme = uri.getScheme() == null? "http" : uri.getScheme();
29         String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
30         int port = uri.getPort();
31         if (port == -1) {
32             if ("http".equalsIgnoreCase(scheme)) {
33                 port = 80;
34             } else if ("https".equalsIgnoreCase(scheme)) {
35                 port = 443;
36             }
37         }
38
39         if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
40             System.err.println("Only HTTP(S) is supported.");
41             return;
42         }
43
44         // Configure SSL context if necessary.
45         final boolean ssl = "https".equalsIgnoreCase(scheme);
46         final SslContext sslCtx;
47         if (ssl) {
48             sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
49         } else {
50             sslCtx = null;
51         }
52
53         // Configure the client.
54         EventLoopGroup group = new NioEventLoopGroup();
55         try {
56             Bootstrap b = new Bootstrap();
57             b.group(group)
58              .channel(NioSocketChannel.class)
59              .handler(new HttpSnoopClientInitializer(sslCtx));
60
61             // Make the connection attempt.
62             Channel ch = b.connect(host, port).sync().channel();
63             System.out.println("*************"+uri.getRawQuery()+"*************");
64             // Prepare the HTTP request.
65             HttpRequest request = new DefaultFullHttpRequest(
66                     HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()+PARAM);
67             request.headers().set(HttpHeaders.Names.HOST, host);
68             request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
69             request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
70
71             // Set some example cookies.
72             request.headers().set(
73                     HttpHeaders.Names.COOKIE,
74                     ClientCookieEncoder.encode(
75                             new DefaultCookie("my-cookie", "foo"),
76                             new DefaultCookie("another-cookie", "bar")));
77
78             // Send the HTTP request.
79             ch.writeAndFlush(request);
80
81             // Wait for the server to close the connection.
82             ch.closeFuture().sync();
83         } finally {
84             // Shut down executor threads to exit.
85             group.shutdownGracefully();
86         }
87     }
88 }
HttpSnoopClientHandler.java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil;

public class HttpSnoopClientHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;

            System.err.println("STATUS: " + response.getStatus());
            System.err.println("VERSION: " + response.getProtocolVersion());
            System.err.println();

            if (!response.headers().isEmpty()) {
                for (String name: response.headers().names()) {
                    for (String value: response.headers().getAll(name)) {
                        System.err.println("HEADER: " + name + " = " + value);
                    }
                }
                System.err.println();
            }

            if (HttpHeaders.isTransferEncodingChunked(response)) {
                System.err.println("CHUNKED CONTENT {");
            } else {
                System.err.println("CONTENT {");
            }
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;

            System.err.print(content.content().toString(CharsetUtil.UTF_8));
            System.err.flush();

            if (content instanceof LastHttpContent) {
                System.err.println("} END OF CONTENT");
                ctx.close();
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

HttpSnoopClientInitializer.java

 1 import io.netty.channel.ChannelInitializer;
 2 import io.netty.channel.ChannelPipeline;
 3 import io.netty.channel.socket.SocketChannel;
 4 import io.netty.handler.codec.http.HttpClientCodec;
 5 import io.netty.handler.codec.http.HttpContentDecompressor;
 6 import io.netty.handler.ssl.SslContext;
 7
 8 public class HttpSnoopClientInitializer extends ChannelInitializer<SocketChannel> {
 9
10     private final SslContext sslCtx;
11
12     public HttpSnoopClientInitializer(SslContext sslCtx) {
13         this.sslCtx = sslCtx;
14     }
15
16     @Override
17     public void initChannel(SocketChannel ch) {
18         ChannelPipeline p = ch.pipeline();
19
20         // Enable HTTPS if necessary.
21         if (sslCtx != null) {
22             p.addLast(sslCtx.newHandler(ch.alloc()));
23         }
24
25         p.addLast(new HttpClientCodec());
26
27         // Remove the following line if you don‘t want automatic content decompression.
28         p.addLast(new HttpContentDecompressor());
29
30         // Uncomment the following line if you don‘t want to handle HttpContents.
31         //p.addLast(new HttpObjectAggregator(1048576));
32
33         p.addLast(new HttpSnoopClientHandler());
34     }
35 }
时间: 2024-08-02 06:49:26

netty4 HTTPclient 可添加参数的相关文章

httpclient发送无参数的post数据

两个问题: 1.httpclient如何发送一个没有任何参数的post数据呢? 2.Web工程如何去接收一个无参数的post呢? 起因: 今天(2014.11.10)在开发中碰到了一个问题,接口提供方提供的接口是要求使用post方式发送数据的,心想这不超简单的一个东西吗?直接post过去不就是了,但是,提供的接口是没有任何参数的,不是类似这种http://api.dutycode.com/data/parm=xxx这种接口,而是http://api.dutycode.com/data.这个地址直

【Unity3D】【NGUI】如何动态给EventDelegate添加参数

NGUI讨论群:333417608 NGUI版本:3.6.8 注意:参数必须是公共成员变量,不能是栈上的.或者私有的(就是临时在函数里面定义的或者是函数的参数都不行) using UnityEngine; using System.Collections; public class SZEventDelegateParams : MonoBehaviour { public int param = 2; void Start() { // 创建新的delegate,最后调用此(this)脚本的F

Windows 如何为绿色软件运行时添加参数 如最小化,无窗口运行

1 有些软件运行的时候需要或者可以添加参数来实现一些特殊要求,比如开机自启动,运行时不显示主界面,不显示托盘图标等,比如下面的这个流量精灵软件,"urlcore.exe /h /r /t 4956102,4956110,4956111"表示运行urlcore.exe这个程序,同时/h /r /t分别含义如下,最后的三个数字表示要刷的网址编号. [/h] 运行时隐藏界面(hide) [/r] 设置开机自动运行(autorun) [/t] 设置运行时不显示托盘图标(trayicon) ?

XgCalendar日历插件动态添加参数

在使用xgcalendar日历插件的时候,参数数组并非只有类型.显示时间.时区等这些参数,还可以根据extParam自定义参数扩展搜索条件,例如根据用户Id搜索不同用户的日历信息,需要将用户的Id存在参数数组中,代码如下:触发搜索函数时添加参数数组 $("#checkbtn").click(function (e) { var id = $('#ccLUser').combobox('getValue'); if (id!= "") { var json = { e

我的Spring之旅(二):为请求添加参数

1.前言 在上一篇我的Spring之旅(一)中,我们只是利用不带参数的请求返回一个网页或一段json,在实际的B/S.C/S网络交互中,请求中需要自定义的参数.本篇将简单地为之前的请求添加参数. 2.参数说明 ①method:API名称,用于区分服务端调用方法 ②name:请求参数名称,将作为method方法的实参 3.改写HelloController.java package com.nextgame.web; import java.io.IOException; import net.s

RDLC中添加参数,用来显示报表中数据集之外的信息。

我添加了两个参数,首先后台: ReportParameter rp = new ReportParameter("SignInTime", new DateTime(2001,01,01).ToString()); ReportParameter rp1 = new ReportParameter("Types", "本季度"); reportViewer.LocalReport.SetParameters((new ReportParamete

android HttpClient 附带的参数

Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path

Extjs中给同一个GridPanel中的事件添加参数的方法

Extjs中给同一个GridPanel中的事件添加参数的方法: this.isUse = new Ext.Action({            text:'启用',            scope:this,            handler:this.isUseWin.createDelegate (this,[1])        });        this.isNotUse = new Ext.Action({            text:'停用',            

shell下alias 添加参数

alias 默认是无法添加参数的,要想添加参数,只能定义一个函数来调用,示例如下: alias tcstart='new() { /root/bin/tc-single-start "$1"; /root/bin/tclog "$1"; }; new' 其中注意: { /root/bin/tc-single-start 之间要有空格 "$1"; } 之间 要有分号.