List of usage examples for io.netty.handler.codec.http HttpMethod GET
HttpMethod GET
To view the source code for io.netty.handler.codec.http HttpMethod GET.
Click Source Link
From source file:Netty4.book.http.upload.HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size)./* w w w . j ava 2s . c om*/ * * @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 List<Entry<String, String>> entries = headers.entries(); channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:nettyTest.http.HttpHelloWorldClient.java
License:Apache License
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 (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return;//from ww w.j a v a 2 s . co m } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000) .handler(new HttpHelloWorldClientInitializer()); // 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(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX .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(); } }
From source file:nettyTest.httpSsl.oneWay.HttpsHelloWorldClient.java
License:Apache License
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;//from w ww.j a v a 2 s .co m } 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) { File certificate = new File( HttpsHelloWorldServer.class.getClassLoader().getResource("nettyca/google.crt").getFile()); //TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //TrustManagerFactory instance = SimpleTrustManagerFactory.getInstance(SimpleTrustManagerFactory.getDefaultAlgorithm()); TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); //TrustManagerFactory instance = FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = null; instance.init(keyStore); TrustManager[] tms = instance.getTrustManagers(); //instance.init(null); sslCtx = SslContextBuilder.forClient().trustManager(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 HttpsHelloWorldClientInitializer(sslCtx, host, port)); // 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(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX .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(); } }
From source file:org.aotorrent.common.connection.HTTPTrackerConnection.java
License:Apache License
@Override protected void obtainPeers() { try {/* w w w . j av a 2s . c om*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); p.addLast("codec-http", new HttpClientCodec()); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new TrackerConnectionHandler()); } }); Channel ch = b.connect(address).sync().channel(); HTTPTrackerRequest trackerRequest = new HTTPTrackerRequest(uri, infoHash, peerId, localAddress.getPort(), 0, 0, 0, COMPACT, NO_PEER_ID, NUM_WANT, trackerId); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, trackerRequest.createRequest()); final StringBuilder host = new StringBuilder().append(uri.getHost()); if (uri.getPort() > 0 && uri.getPort() != 80) { host.append(":").append(uri.getPort()); } request.headers().set(HttpHeaders.Names.HOST, host.toString()); request.headers().set(HttpHeaders.Names.USER_AGENT, "AOTorrent/0.1"); request.headers().set(HttpHeaders.Names.ACCEPT, "*/*"); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); ch.writeAndFlush(request); ch.closeFuture().sync(); } catch (InterruptedException e) { LOGGER.error("Tracker connection interrupted"); } }
From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java
License:Apache License
public Connection createConnection() { if (channelClazz == null) { return null; }// ww w . j ava2 s . c om // HORNETQ-907 - strip off IPv6 scope-id (if necessary) SocketAddress remoteDestination = new InetSocketAddress(host, port); InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress(); if (inetAddress instanceof Inet6Address) { Inet6Address inet6Address = (Inet6Address) inetAddress; if (inet6Address.getScopeId() != 0) { try { remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort()); } catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } } } ActiveMQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination); ChannelFuture future; //port 0 does not work so only use local address if set if (localPort != 0) { SocketAddress localDestination; if (localAddress != null) { localDestination = new InetSocketAddress(localAddress, localPort); } else { localDestination = new InetSocketAddress(localPort); } future = bootstrap.connect(remoteDestination, localDestination); } else { future = bootstrap.connect(remoteDestination); } future.awaitUninterruptibly(); if (future.isSuccess()) { final Channel ch = future.channel(); SslHandler sslHandler = ch.pipeline().get(SslHandler.class); if (sslHandler != null) { Future<Channel> handshakeFuture = sslHandler.handshakeFuture(); if (handshakeFuture.awaitUninterruptibly(30000)) { if (handshakeFuture.isSuccess()) { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } else { ch.close().awaitUninterruptibly(); ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause()); return null; } } else { //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds")); ch.close().awaitUninterruptibly(); return null; } } if (httpUpgradeEnabled) { // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler. try { //get this first incase it removes itself HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade"); URI uri = new URI("http", null, host, port, null, null, null); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); final String endpoint = ConfigurationHelper.getStringProperty( TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration); if (endpoint != null) { request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint); } // Get 16 bit nonce and base 64 encode it byte[] nonce = randomBytes(16); String key = base64(nonce); request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key); ch.attr(REMOTING_KEY).set(key); ActiveMQClientLogger.LOGGER.debugf("Sending HTTP request %s", request); // Send the HTTP request. ch.writeAndFlush(request); if (!httpUpgradeHandler.awaitHandshake()) { return null; } } catch (URISyntaxException e) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e); return null; } } else { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } // No acceptor on a client connection Listener connectionListener = new Listener(); NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false); connectionListener.connectionCreated(null, conn, protocolManager.getName()); return conn; } else { Throwable t = future.cause(); if (t != null && !(t instanceof ConnectException)) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause()); } return null; } }
From source file:org.apache.activemq.artemis.test.WebServerComponentTest.java
License:Apache License
@Test public void simpleServer() throws Exception { WebServerDTO webServerDTO = new WebServerDTO(); webServerDTO.bind = "http://localhost:8161"; webServerDTO.path = "webapps"; WebServerComponent webServerComponent = new WebServerComponent(); webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/"); webServerComponent.start();/* w ww . j ava 2s.c o m*/ // Make the connection attempt. CountDownLatch latch = new CountDownLatch(1); final ClientHandler clientHandler = new ClientHandler(latch); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(clientHandler); } }); Channel ch = bootstrap.connect("localhost", 8161).sync().channel(); URI uri = new URI(URL); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, "localhost"); // Send the HTTP request. ch.writeAndFlush(request); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(clientHandler.body, "12345"); // Wait for the server to close the connection. ch.close(); webServerComponent.stop(); }
From source file:org.apache.activemq.cli.test.WebServerComponentTest.java
License:Apache License
@Test public void simpleServer() throws Exception { WebServerDTO webServerDTO = new WebServerDTO(); webServerDTO.bind = "http://localhost:0"; webServerDTO.path = "webapps"; WebServerComponent webServerComponent = new WebServerComponent(); Assert.assertFalse(webServerComponent.isStarted()); webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/"); testedComponents.add(webServerComponent); webServerComponent.start();//from w ww. j a va2 s . c o m final int port = webServerComponent.getPort(); // Make the connection attempt. CountDownLatch latch = new CountDownLatch(1); final ClientHandler clientHandler = new ClientHandler(latch); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(clientHandler); } }); Channel ch = bootstrap.connect("localhost", port).sync().channel(); URI uri = new URI(URL); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, "localhost"); // Send the HTTP request. ch.writeAndFlush(request); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(clientHandler.body, "12345"); assertNull(clientHandler.serverHeader); // Wait for the server to close the connection. ch.close(); Assert.assertTrue(webServerComponent.isStarted()); webServerComponent.stop(true); Assert.assertFalse(webServerComponent.isStarted()); }
From source file:org.apache.activemq.cli.test.WebServerComponentTest.java
License:Apache License
@Test public void testComponentStopBehavior() throws Exception { WebServerDTO webServerDTO = new WebServerDTO(); webServerDTO.bind = "http://localhost:0"; webServerDTO.path = "webapps"; WebServerComponent webServerComponent = new WebServerComponent(); Assert.assertFalse(webServerComponent.isStarted()); webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/"); webServerComponent.start();//ww w . ja va 2s . co m final int port = webServerComponent.getPort(); // Make the connection attempt. CountDownLatch latch = new CountDownLatch(1); final ClientHandler clientHandler = new ClientHandler(latch); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(clientHandler); } }); Channel ch = bootstrap.connect("localhost", port).sync().channel(); URI uri = new URI(URL); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, "localhost"); // Send the HTTP request. ch.writeAndFlush(request); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(clientHandler.body, "12345"); // Wait for the server to close the connection. ch.close(); Assert.assertTrue(webServerComponent.isStarted()); //usual stop won't actually stop it webServerComponent.stop(); assertTrue(webServerComponent.isStarted()); webServerComponent.stop(true); Assert.assertFalse(webServerComponent.isStarted()); }
From source file:org.apache.activemq.cli.test.WebServerComponentTest.java
License:Apache License
@Test public void simpleSecureServer() throws Exception { WebServerDTO webServerDTO = new WebServerDTO(); webServerDTO.bind = "https://localhost:0"; webServerDTO.path = "webapps"; webServerDTO.keyStorePath = "./src/test/resources/server.keystore"; webServerDTO.setKeyStorePassword("password"); WebServerComponent webServerComponent = new WebServerComponent(); Assert.assertFalse(webServerComponent.isStarted()); webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/"); testedComponents.add(webServerComponent); webServerComponent.start();//from w w w .j ava2s . c o m final int port = webServerComponent.getPort(); // Make the connection attempt. SSLContext context = new SSLSupport().setKeystorePath(webServerDTO.keyStorePath) .setKeystorePassword(webServerDTO.getKeyStorePassword()) .setTruststorePath(webServerDTO.keyStorePath) .setTruststorePassword(webServerDTO.getKeyStorePassword()).createContext(); SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); final SslHandler sslHandler = new SslHandler(engine); CountDownLatch latch = new CountDownLatch(1); final ClientHandler clientHandler = new ClientHandler(latch); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(clientHandler); } }); Channel ch = bootstrap.connect("localhost", port).sync().channel(); URI uri = new URI(SECURE_URL); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, "localhost"); // Send the HTTP request. ch.writeAndFlush(request); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(clientHandler.body, "12345"); assertNull(clientHandler.serverHeader); // Wait for the server to close the connection. ch.close(); Assert.assertTrue(webServerComponent.isStarted()); webServerComponent.stop(true); Assert.assertFalse(webServerComponent.isStarted()); }
From source file:org.apache.activemq.cli.test.WebServerComponentTest.java
License:Apache License
@Test public void simpleSecureServerWithClientAuth() throws Exception { WebServerDTO webServerDTO = new WebServerDTO(); webServerDTO.bind = "https://localhost:0"; webServerDTO.path = "webapps"; webServerDTO.keyStorePath = "./src/test/resources/server.keystore"; webServerDTO.setKeyStorePassword("password"); webServerDTO.clientAuth = true;/*from w w w . j a va2 s . c om*/ webServerDTO.trustStorePath = "./src/test/resources/server.keystore"; webServerDTO.setTrustStorePassword("password"); WebServerComponent webServerComponent = new WebServerComponent(); Assert.assertFalse(webServerComponent.isStarted()); webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/"); testedComponents.add(webServerComponent); webServerComponent.start(); final int port = webServerComponent.getPort(); // Make the connection attempt. SSLContext context = new SSLSupport().setKeystorePath(webServerDTO.keyStorePath) .setKeystorePassword(webServerDTO.getKeyStorePassword()) .setTruststorePath(webServerDTO.trustStorePath) .setTruststorePassword(webServerDTO.getTrustStorePassword()).createContext(); SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); final SslHandler sslHandler = new SslHandler(engine); CountDownLatch latch = new CountDownLatch(1); final ClientHandler clientHandler = new ClientHandler(latch); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(clientHandler); } }); Channel ch = bootstrap.connect("localhost", port).sync().channel(); URI uri = new URI(SECURE_URL); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, "localhost"); // Send the HTTP request. ch.writeAndFlush(request); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(clientHandler.body, "12345"); // Wait for the server to close the connection. ch.close(); Assert.assertTrue(webServerComponent.isStarted()); webServerComponent.stop(true); Assert.assertFalse(webServerComponent.isStarted()); }