use of io.netty.handler.codec.http.HttpRequest in project netty by netty.
the class SpdyClient method main.
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.SPDY_3_1, ApplicationProtocolNames.HTTP_1_1)).build();
HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.remoteAddress(HOST, PORT);
b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));
// Start the client.
Channel channel = b.connect().syncUninterruptibly().channel();
System.out.println("Connected to " + HOST + ':' + PORT);
// Create a GET request.
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
request.headers().set(HttpHeaderNames.HOST, HOST);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// Send the GET request.
channel.writeAndFlush(request).sync();
// Waits for the complete HTTP response
httpResponseHandler.queue().take().sync();
System.out.println("Finished SPDY HTTP GET");
// Wait until the connection is closed.
channel.close().syncUninterruptibly();
} finally {
workerGroup.shutdownGracefully();
}
}
use of io.netty.handler.codec.http.HttpRequest in project netty by netty.
the class HttpUploadClient method formget.
/**
* 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();
}
use of io.netty.handler.codec.http.HttpRequest in project async-http-client by AsyncHttpClient.
the class BasicHttpsTest method multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy.
@Test
public void multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy() throws Throwable {
logger.debug(">>> multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy");
KeepAliveStrategy keepAliveStrategy = new KeepAliveStrategy() {
@Override
public boolean keepAlive(Request ahcRequest, HttpRequest nettyRequest, HttpResponse nettyResponse) {
return !ahcRequest.getUri().isSecured();
}
};
withClient(config().setSslEngineFactory(createSslEngineFactory()).setKeepAliveStrategy(keepAliveStrategy)).run(client -> {
withServer(server).run(server -> {
server.enqueueEcho();
server.enqueueEcho();
server.enqueueEcho();
String body = "hello there";
client.preparePost(getTargetUrl()).setBody(body).setHeader(CONTENT_TYPE, "text/html").execute();
client.preparePost(getTargetUrl()).setBody(body).setHeader(CONTENT_TYPE, "text/html").execute();
Response response = client.preparePost(getTargetUrl()).setBody(body).setHeader(CONTENT_TYPE, "text/html").execute().get();
assertEquals(response.getResponseBody(), body);
});
});
logger.debug("<<< multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy");
}
use of io.netty.handler.codec.http.HttpRequest in project async-http-client by AsyncHttpClient.
the class NettyConnectListener method writeRequest.
private void writeRequest(Channel channel) {
if (futureIsAlreadyCancelled(channel)) {
return;
}
if (LOGGER.isDebugEnabled()) {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
LOGGER.debug("Using new Channel '{}' for '{}' to '{}'", channel, httpRequest.method(), httpRequest.uri());
}
Channels.setAttribute(channel, future);
channelManager.registerOpenChannel(channel, partitionKey);
future.attachChannel(channel, false);
requestSender.writeRequest(future, channel);
}
use of io.netty.handler.codec.http.HttpRequest in project async-http-client by AsyncHttpClient.
the class NettyRequestSender method sendRequestWithOpenChannel.
private <T> ListenableFuture<T> sendRequestWithOpenChannel(Request request, ProxyServer proxy, NettyResponseFuture<T> future, AsyncHandler<T> asyncHandler, Channel channel) {
if (asyncHandler instanceof AsyncHandlerExtensions)
AsyncHandlerExtensions.class.cast(asyncHandler).onConnectionPooled(channel);
TimeoutsHolder timeoutsHolder = scheduleRequestTimeout(future);
timeoutsHolder.initRemoteAddress((InetSocketAddress) channel.remoteAddress());
future.setChannelState(ChannelState.POOLED);
future.attachChannel(channel, false);
if (LOGGER.isDebugEnabled()) {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
LOGGER.debug("Using open Channel {} for {} '{}'", channel, httpRequest.method(), httpRequest.uri());
}
// channelInactive might be called between isChannelValid and writeRequest
// so if we don't store the Future now, channelInactive won't perform handleUnexpectedClosedChannel
Channels.setAttribute(channel, future);
if (Channels.isChannelValid(channel)) {
writeRequest(future, channel);
} else {
// bad luck, the channel was closed in-between
// there's a very good chance onClose was already notified but the
// future wasn't already registered
handleUnexpectedClosedChannel(channel, future);
}
return future;
}
Aggregations