下面列出了怎么用 io.netty.handler.codec.http.cookie.ClientCookieEncoder 的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void extractCookies_works_if_cookies_defined_in_headers() {
// given
Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));
HttpRequest nettyRequestMock = mock(HttpRequest.class);
doReturn(headers).when(nettyRequestMock).headers();
// when
Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);
// then
assertThat(extractedCookies.contains(cookie1), is(true));
assertThat(extractedCookies.contains(cookie2), is(true));
}
@Test
public void extractCookies_works_if_cookies_defined_in_trailing_headers() {
// given
Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
HttpHeaders trailingHeaders = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));
FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
doReturn(new DefaultHttpHeaders()).when(nettyRequestMock).headers();
doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();
// when
Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);
// then
assertThat(extractedCookies.contains(cookie1), is(true));
assertThat(extractedCookies.contains(cookie2), is(true));
}
@Test
public void extractCookies_handles_cookie_values_leniently() {
// given
//these are cookie values seen in the wild...
Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), "2094%3Az%7C2021%3Ab");
Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), "geoloc=cc=US,rc=OR,tp=vhigh,tz=PST,la=45.4978,lo=-122.6937,bw=5000");
Cookie cookie3 = new DefaultCookie(UUID.randomUUID().toString(), "\"dm=n.com&si=27431295-a282-4745-8cd5-542e7fce" +
"429e&ss=1477551008358&sl=76&tt=437632&obo=12&sh=1477552753923%3D76%3A12%3A437632%2C1477552698670%3D75%3" +
"A12%3A429879%2C1477552677137%3D74%3A12%3A426596%2C1477552672564%3D73%3A12%3A425585%2C1477552669893%3D72" +
"%3A12%3A423456&bcn=%2F%2F3408178b.mpstat.us%2F&ld=1477552753923&r=http%3A%2F%2Fwww.nike.com%2Fbe%2Fde_de%" +
"2F&ul=1477552756811\"");
HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2, cookie3));
HttpRequest nettyRequestMock = mock(HttpRequest.class);
doReturn(headers).when(nettyRequestMock).headers();
// when
Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);
// then
assertThat(extractedCookies.contains(cookie1), is(true));
assertThat(extractedCookies.contains(cookie2), is(true));
assertThat(extractedCookies.contains(cookie3), is(true));
}
public static HttpResponse createServerDefault(String requestCookie) {
HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());
ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
if (requestCookie == null) { return ret; }
Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie);
if (cookies.isEmpty()) { return ret; }
// Reset the cookies if necessary.
for (Cookie cookie : cookies) {
ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie));
}
return ret;
}
@Test
public void addDecoderReplaysLastHttp() {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT)
.addHandler(new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
MatcherAssert.assertThat(channel.pipeline().names().iterator().next(), is("JsonObjectDecoder$extractor"));
Object content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
MatcherAssert.assertThat(channel.readInbound(), nullValue());
}
@Test
public void addNamedDecoderReplaysLastHttp() {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT)
.addHandler("json", new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
MatcherAssert.assertThat(channel.pipeline().names().iterator().next(), is("json$extractor"));
Object content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
MatcherAssert.assertThat(channel.readInbound(), nullValue());
}
@Test
public void addEncoderReplaysLastHttp() {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT)
.addHandler(new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
MatcherAssert.assertThat(channel.pipeline().names().iterator().next(), is("JsonObjectDecoder$extractor"));
Object content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
MatcherAssert.assertThat(channel.readInbound(), nullValue());
}
@Test
public void addNamedEncoderReplaysLastHttp() {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT)
.addHandler("json", new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
MatcherAssert.assertThat(channel.pipeline().names().iterator().next(), is("json$extractor"));
Object content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(ByteBuf.class));
((ByteBuf) content).release();
content = channel.readInbound();
MatcherAssert.assertThat(content, instanceOf(LastHttpContent.class));
((LastHttpContent) content).release();
MatcherAssert.assertThat(channel.readInbound(), nullValue());
}
public static FullHttpRequest makeEppHttpRequest(
String content,
String host,
String path,
String accessToken,
String sslClientCertificateHash,
String clientAddress,
Cookie... cookies) {
FullHttpRequest request = makeHttpPostRequest(content, host, path);
request
.headers()
.set("authorization", "Bearer " + accessToken)
.set("content-type", "application/epp+xml")
.set("accept", "application/epp+xml")
.set("X-SSL-Certificate", sslClientCertificateHash)
.set("X-Forwarded-For", clientAddress);
if (cookies.length != 0) {
request.headers().set("cookie", ClientCookieEncoder.STRICT.encode(cookies));
}
return request;
}
private void prepareRequest(HttpContext<?> context) {
HttpRequestImpl<?> request = (HttpRequestImpl<?>) context.request();
WebClientSessionAware webclient = (WebClientSessionAware) request.client;
MultiMap headers = context.get(HEADERS_CONTEXT_KEY);
if (headers == null) {
headers = HttpHeaders.headers().addAll(request.headers());
context.set(SessionAwareInterceptor.HEADERS_CONTEXT_KEY, headers);
}
// we need to reset the headers at every "send" because cookies can be changed,
// either by the server (that sent new ones) or by the user.
request.headers().clear().addAll(headers).addAll(webclient.headers());
String domain = request.virtualHost();
if (domain == null) {
domain = request.host();
}
Iterable<Cookie> cookies = webclient.cookieStore().get(request.ssl, domain, request.uri);
for (Cookie c : cookies) {
request.headers().add("cookie", ClientCookieEncoder.STRICT.encode(c));
}
}
private void prepareRedirectRequest(HttpContext<?> context) {
// Now the context contains the redirect request in clientRequest() and the original request in request()
HttpClientRequest redirectRequest = context.clientRequest();
HttpRequestImpl<?> originalRequest = (HttpRequestImpl<?>) context.request();
WebClientSessionAware webclient = (WebClientSessionAware) originalRequest.client;
MultiMap headers = context.get(HEADERS_CONTEXT_KEY);
if (headers == null) {
headers = HttpHeaders.headers().addAll(redirectRequest.headers());
context.set(SessionAwareInterceptor.HEADERS_CONTEXT_KEY, headers);
}
String redirectHost = URI.create(redirectRequest.absoluteURI()).getHost();
String domain;
if (redirectHost.equals(originalRequest.host()) && originalRequest.virtualHost != null) {
domain = originalRequest.virtualHost;
} else {
domain = redirectHost;
}
Iterable<Cookie> cookies = webclient.cookieStore().get(originalRequest.ssl, domain, redirectRequest.path());
for (Cookie c : cookies) {
redirectRequest.headers().add("cookie", ClientCookieEncoder.STRICT.encode(c));
}
}
/**
* Encodes a collection of {@link RequestCookie} objects into a "Cookie" header value.
*
* @param cookies cookies
* @return "Cookie" header value
*/
public static String encode(Collection<RequestCookie> cookies) {
if (cookies.isEmpty()) {
throw new IllegalArgumentException("Cannot create cookie header value from zero cookies");
}
Set<Cookie> nettyCookies = cookies.stream()
.map(RequestCookie::convert)
.collect(toSet());
return ClientCookieEncoder.LAX.encode(nettyCookies);
}
@Before
public void setup() throws Exception {
s = new Server(conf);
s.run();
Connector con = mac.getConnector("root", "secret");
con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));
this.sessionId = UUID.randomUUID().toString();
AuthCache.getCache().put(sessionId, token);
group = new NioEventLoopGroup();
SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
HttpHeaders headers = new DefaultHttpHeaders();
headers.add(HttpHeaderNames.COOKIE, cookieVal);
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
WebSocketVersion.V13, (String) null, false, headers);
handler = new ClientHandler(handshaker);
Bootstrap boot = new Bootstrap();
boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
ch.pipeline().addLast(new HttpClientCodec());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(handler);
}
});
ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
// Wait until handshake is complete
while (!handshaker.isHandshakeComplete()) {
sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
LOG.debug("Waiting for Handshake to complete");
}
}
@Before
public void setup() throws Exception {
s = new Server(conf);
s.run();
Connector con = mac.getConnector("root", "secret");
con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));
this.sessionId = UUID.randomUUID().toString();
AuthCache.put(sessionId, TimelyPrincipal.anonymousPrincipal());
group = new NioEventLoopGroup();
SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
HttpHeaders headers = new DefaultHttpHeaders();
headers.add(HttpHeaderNames.COOKIE, cookieVal);
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
WebSocketVersion.V13, (String) null, false, headers);
handler = new ClientHandler(handshaker);
Bootstrap boot = new Bootstrap();
boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
ch.pipeline().addLast(new HttpClientCodec());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(handler);
}
});
ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
// Wait until handshake is complete
while (!handshaker.isHandshakeComplete()) {
sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
LOG.debug("Waiting for Handshake to complete");
}
}
protected void normalize() {
normalizeParameters();
String encoded = ClientCookieEncoder.STRICT.encode(cookies);
if (encoded == null) { return; }
headers().set(HttpHeaderNames.COOKIE, encoded);
}
HttpClientConfig(ConnectionProvider connectionProvider, Map<ChannelOption<?>, ?> options,
Supplier<? extends SocketAddress> remoteAddress) {
super(connectionProvider, options, remoteAddress);
this.acceptGzip = false;
this.cookieDecoder = ClientCookieDecoder.STRICT;
this.cookieEncoder = ClientCookieEncoder.STRICT;
this.decoder = new HttpResponseDecoderSpec();
this.headers = new DefaultHttpHeaders();
this.method = HttpMethod.GET;
this.protocols = new HttpProtocol[]{HttpProtocol.HTTP11};
this._protocols = h11;
this.retryDisabled = false;
}
HttpClientOperations(Connection c, ConnectionObserver listener, ClientCookieEncoder encoder, ClientCookieDecoder decoder) {
super(c, listener);
this.isSecure = c.channel()
.pipeline()
.get(NettyPipeline.SslHandler) != null;
this.nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
this.requestHeaders = nettyRequest.headers();
this.cookieDecoder = decoder;
this.cookieEncoder = encoder;
}
@Test
public void testConstructorWithProvidedReplacement() {
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addFirst(NettyPipeline.SslHandler, new ChannelHandlerAdapter() {
});
HttpClientOperations ops1 = new HttpClientOperations(() -> channel,
ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT);
ops1.followRedirectPredicate((req, res) -> true);
ops1.started = true;
ops1.retrying = true;
ops1.redirecting = new RedirectClientException(new DefaultHttpHeaders().add(HttpHeaderNames.LOCATION, "/"));
HttpClientOperations ops2 = new HttpClientOperations(ops1);
assertSame(ops1.channel(), ops2.channel());
assertSame(ops1.started, ops2.started);
assertSame(ops1.retrying, ops2.retrying);
assertSame(ops1.redirecting, ops2.redirecting);
assertSame(ops1.redirectedFrom, ops2.redirectedFrom);
assertSame(ops1.isSecure, ops2.isSecure);
assertSame(ops1.nettyRequest, ops2.nettyRequest);
assertSame(ops1.responseState, ops2.responseState);
assertSame(ops1.followRedirectPredicate, ops2.followRedirectPredicate);
assertSame(ops1.requestHeaders, ops2.requestHeaders);
}
private void doTestStatus(HttpResponseStatus status) {
EmbeddedChannel channel = new EmbeddedChannel();
HttpClientOperations ops = new HttpClientOperations(() -> channel,
ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT);
ops.setNettyResponse(new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.EMPTY_BUFFER));
assertEquals(status.reasonPhrase(), ops.status().reasonPhrase());
}
@Override
public void onRequestSuccessed(ChannelHandlerContext ctx,
HttpResponse response) {
NettyHttpSession s = HttpSessionThreadLocal.get();
if (s != null && !this.sessionRequestedByCookie) {
// setup the Cookie for session
response.headers().set(HttpHeaderNames.SET_COOKIE,
ClientCookieEncoder.STRICT.encode(NettyHttpSession.SESSION_ID_KEY, s.getId()));
}
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
*
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String, String>> formget(
Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
Channel channel = bootstrap.connect(host, port).sync().channel();
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform", "GET");
encoder.addParam("info", "first value");
encoder.addParam("secondinfo", "secondvalue ���&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send", "Send");
URI uriGet = new URI(encoder.toString());
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");
//connection will not close but needed
// headers.set("Connection","keep-alive");
// headers.set("Keep-Alive","300");
headers.set(
HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))
);
// send request
channel.writeAndFlush(request);
// Wait for the server to close the connection.
channel.closeFuture().sync();
// convert headers to list
return headers.entries();
}
public static void main(String[] args) throws Exception {
URI uri = new URI(URL);
String scheme = uri.getScheme() == null? "http" : uri.getScheme();
String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
if (port == -1) {
if ("http".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("https".equalsIgnoreCase(scheme)) {
port = 443;
}
}
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
System.err.println("Only HTTP(S) is supported.");
return;
}
// Configure SSL context if necessary.
final boolean ssl = "https".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new HttpSnoopClientInitializer(sslCtx));
// Make the connection attempt.
Channel ch = b.connect(host, port).sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// Set some example cookies.
request.headers().set(
HttpHeaderNames.COOKIE,
ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar")));
// Send the HTTP request.
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
URI uri = new URI(URL);
String scheme = uri.getScheme() == null? "http" : uri.getScheme();
String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
if (port == -1) {
if ("http".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("https".equalsIgnoreCase(scheme)) {
port = 443;
}
}
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
System.err.println("Only HTTP(S) is supported.");
return;
}
// 配置 SSL context.
final boolean ssl = "https".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextGMBuilder.forClient()
.trustManager(SslContextGMBuilderTest.TRUST_CERT)
.keyManager(SslContextGMBuilderTest.ENC_CERT, SslContextGMBuilderTest.ENC_KEY, SslContextGMBuilderTest.SIGN_CERT, SslContextGMBuilderTest.SIGN_KEY, null)
.build();
} else {
sslCtx = null;
}
// 配置客户端 client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new HttpSnoopClientInitializer(sslCtx));
// 尝试连接.
Channel ch = b.connect(host, port).sync().channel();
// 准备HTTP请求参数.
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// 设置演示用的 cookies.
request.headers().set(
HttpHeaderNames.COOKIE,
ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar")));
// 发送 HTTP 请求.
ch.writeAndFlush(request);
// 等待服务器关闭连接.
ch.closeFuture().sync();
} finally {
// 关闭执行线程来退出客户端.
group.shutdownGracefully();
}
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
*
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String, String>> formget(
Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
Channel channel = bootstrap.connect(host, port).sync().channel();
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform", "GET");
encoder.addParam("info", "first value");
encoder.addParam("secondinfo", "secondvalue ���&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send", "Send");
URI uriGet = new URI(encoder.toString());
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");
//connection will not close but needed
// headers.set("Connection","keep-alive");
// headers.set("Keep-Alive","300");
headers.set(
HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))
);
// send request
channel.writeAndFlush(request);
// Wait for the server to close the connection.
channel.closeFuture().sync();
// convert headers to list
return headers.entries();
}
public static void main(String[] args) throws Exception {
URI uri = new URI(URL);
String scheme = uri.getScheme() == null? "http" : uri.getScheme();
String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
if (port == -1) {
if ("http".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("https".equalsIgnoreCase(scheme)) {
port = 443;
}
}
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
System.err.println("Only HTTP(S) is supported.");
return;
}
// Configure SSL context if necessary.
final boolean ssl = "https".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new HttpSnoopClientInitializer(sslCtx));
// Make the connection attempt.
Channel ch = b.connect(host, port).sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// Set some example cookies.
request.headers().set(
HttpHeaderNames.COOKIE,
ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar")));
// Send the HTTP request.
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}
private void addCookie(FullHttpRequest request) {
request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, cookie));
}
private void addCookie(FullHttpRequest request) {
request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, cookie));
}
@Test
public void netty_helper_constructor_populates_request_info_appropriately() {
// given
String uri = "/some/uri/path/%24foobar%26?foo=bar&secondparam=secondvalue";
Map<String, List<String>> expectedQueryParamMap = new HashMap<>();
expectedQueryParamMap.put("foo", Arrays.asList("bar"));
expectedQueryParamMap.put("secondparam", Arrays.asList("secondvalue"));
HttpMethod method = HttpMethod.PATCH;
String cookieName = UUID.randomUUID().toString();
String cookieValue = UUID.randomUUID().toString();
String content = UUID.randomUUID().toString();
byte[] contentBytes = content.getBytes();
Charset contentCharset = CharsetUtil.UTF_8;
ByteBuf contentByteBuf = Unpooled.copiedBuffer(contentBytes);
HttpHeaders headers = new DefaultHttpHeaders()
.add("header1", "val1")
.add(HttpHeaders.Names.CONTENT_TYPE, contentCharset)
.add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
.add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookieName, cookieValue));
HttpHeaders trailingHeaders = new DefaultHttpHeaders().add("trailingHeader1", "trailingVal1");
HttpVersion protocolVersion = HttpVersion.HTTP_1_1;
FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
doReturn(uri).when(nettyRequestMock).uri();
doReturn(method).when(nettyRequestMock).method();
doReturn(headers).when(nettyRequestMock).headers();
doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();
doReturn(contentByteBuf).when(nettyRequestMock).content();
doReturn(protocolVersion).when(nettyRequestMock).protocolVersion();
// when
RequestInfoImpl<?> requestInfo = new RequestInfoImpl<>(nettyRequestMock);
// then
assertThat("getUri was not the same value sent in", requestInfo.getUri(), is(uri));
assertThat("getPath did not decode as expected", requestInfo.getPath(), is("/some/uri/path/$foobar&"));
assertThat(requestInfo.getMethod(), is(method));
assertThat(requestInfo.getHeaders(), is(headers));
assertThat(requestInfo.getTrailingHeaders(), is(trailingHeaders));
assertThat(requestInfo.getQueryParams(), notNullValue());
assertThat(requestInfo.getQueryParams().parameters(), is(expectedQueryParamMap));
assertThat(requestInfo.getCookies(), is(Sets.newHashSet(new DefaultCookie(cookieName, cookieValue))));
assertThat(requestInfo.pathTemplate, nullValue());
assertThat(requestInfo.pathParams.isEmpty(), is(true));
assertThat(requestInfo.getRawContentBytes(), is(contentBytes));
assertThat(requestInfo.getRawContent(), is(content));
assertThat(requestInfo.content, nullValue());
assertThat(requestInfo.getContentCharset(), is(contentCharset));
assertThat(requestInfo.getProtocolVersion(), is(protocolVersion));
assertThat(requestInfo.isKeepAliveRequested(), is(true));
}
/**
* Configure the
* {@link ClientCookieEncoder}, {@link ClientCookieDecoder} will be
* chosen based on the encoder
*
* @param encoder the preferred ClientCookieEncoder
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookieCodec(ClientCookieEncoder encoder) {
Objects.requireNonNull(encoder, "encoder");
ClientCookieDecoder decoder = encoder == ClientCookieEncoder.LAX ?
ClientCookieDecoder.LAX : ClientCookieDecoder.STRICT;
return cookieCodec(encoder, decoder);
}
/**
* Configure the
* {@link ClientCookieEncoder} and {@link ClientCookieDecoder}
*
* @param encoder the preferred ClientCookieEncoder
* @param decoder the preferred ClientCookieDecoder
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookieCodec(ClientCookieEncoder encoder, ClientCookieDecoder decoder) {
Objects.requireNonNull(encoder, "encoder");
Objects.requireNonNull(decoder, "decoder");
HttpClient dup = duplicate();
dup.configuration().cookieEncoder = encoder;
dup.configuration().cookieDecoder = decoder;
return dup;
}