List of usage examples for io.netty.handler.codec.http DefaultCookie DefaultCookie
public DefaultCookie(String name, String value)
From source file:com.mastfrog.acteur.wicket.EnsureSessionId.java
License:Open Source License
@Inject EnsureSessionId(HttpEvent evt, Application app, Settings settings) { SessionId id = findSessionId(evt);//w w w . j a v a 2 s. c om if (id == null) { id = new SessionId(); DefaultCookie ck = new DefaultCookie(ActeurSessionStore.COOKIE_NAME, id.toString()); long maxAge = Duration.standardHours(settings.getLong(SETTINGS_KEY_SESSION_COOKIE_MAX_AGE_HOURS, DEFAULT_SESSION_COOKIE_MAX_AGE_HOURS)).toStandardSeconds().getSeconds(); ck.setMaxAge(maxAge); add(Headers.SET_COOKIE, ck); String sv = Headers.COOKIE.toString(new Cookie[] { ck }); evt.getRequest().headers().add(Headers.SET_COOKIE.name(), sv); IRequestLogger logger = app.getRequestLogger(); if (logger != null) { logger.sessionCreated(id.toString()); } } setState(new ConsumedLockedState(id)); }
From source file:com.mastfrog.netty.http.client.CookieStore.java
License:Open Source License
@SuppressWarnings("unchecked") public void read(InputStream in) throws IOException { ObjectMapper om = new ObjectMapper(); List<Map<String, Object>> l = om.readValue(in, List.class); List<DateCookie> cks = new ArrayList<>(); for (Map<String, Object> m : l) { String domain = (String) m.get("domain"); Number maxAge = (Number) m.get("maxAge"); Number timestamp = (Number) m.get("timestamp"); String path = (String) m.get("path"); String name = (String) m.get("name"); String value = (String) m.get("value"); Boolean httpOnly = (Boolean) m.get("httpOnly"); Boolean secure = (Boolean) m.get("secure"); String comment = (String) m.get("comment"); String commentUrl = (String) m.get("commentUrl"); List<Integer> ports = (List<Integer>) m.get("ports"); DateTime ts = timestamp == null ? DateTime.now() : new DateTime(timestamp.longValue()); DateCookie cookie = new DateCookie(new DefaultCookie(name, value), ts); if (cookie.isExpired()) { continue; }/*from w ww.j av a2 s . c om*/ if (domain != null) { cookie.setDomain(domain); } if (maxAge != null) { cookie.setMaxAge(maxAge.longValue()); } if (path != null) { cookie.setPath(path); } if (httpOnly != null) { cookie.setHttpOnly(httpOnly); } if (secure != null) { cookie.setSecure(secure); } if (comment != null) { cookie.setComment(comment); } if (commentUrl != null) { cookie.setCommentUrl(commentUrl); } if (ports != null) { cookie.setPorts(ports); } cks.add(cookie); } if (!cks.isEmpty()) { Lock writeLock = lock.writeLock(); try { writeLock.lock(); cookies.addAll(cks); } finally { writeLock.unlock(); } } }
From source file:com.mastfrog.netty.http.client.CookieStoreTest.java
License:Open Source License
@Test public void test() throws IOException { assertTrue(true);//from w w w . j a v a 2s .c om CookieStore store = new CookieStore(); DefaultCookie ck1 = new DefaultCookie("foo", "bar"); DefaultCookie ck2 = new DefaultCookie("one", "two"); ck1.setPath("/foo"); ck1.setDomain("foo.com"); ck1.setMaxAge(10000); ck2.setPath("/foo"); ck2.setDomain("foo.com"); ck2.setMaxAge(10000); DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); resp.headers().add(Headers.SET_COOKIE.name(), Headers.SET_COOKIE.toString(ck1)); resp.headers().add(Headers.SET_COOKIE.name(), Headers.SET_COOKIE.toString(ck2)); store.extract(resp.headers()); Iterator<Cookie> iter = store.iterator(); assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/foo/bar"); req.headers().add(Headers.HOST.name(), "foo.com"); store.decorate(req); List<String> cookieHeaders = req.headers().getAll(Headers.COOKIE.name()); assertEquals(2, cookieHeaders.size()); List<String> find = new LinkedList<>(Arrays.asList("foo", "one")); for (String hdr : cookieHeaders) { Cookie cookie = Headers.SET_COOKIE.toValue(hdr); find.remove(cookie.getName()); } assertTrue("Not found: " + find, find.isEmpty()); CookieStore nue = new CookieStore(store.cookies, true, true); assertEquals(store, nue); ByteArrayOutputStream out = new ByteArrayOutputStream(); store.store(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); nue = new CookieStore(); nue.read(in); assertEquals(store, nue); DefaultCookie ck3 = new DefaultCookie("fuz", "bang"); ck3.setMaxAge(20000); ck3.setPath("/moo/wuzz"); ck3.setDomain("foo.com"); nue.add(ck3); assertNotEquals(store, nue); }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ByteBuf buffer, ProxyServer proxyServer) throws IOException { String host = AsyncHttpProviderUtils.getHost(uri); boolean webSocket = isWebSocket(uri); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); }/* w w w . j a v a 2s . com*/ FullHttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri)); } else { String path = null; if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies())) path = uri.toString(); else if (uri.getRawQuery() != null) path = uri.getRawPath() + "?" + uri.getRawQuery(); else path = uri.getRawPath(); nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, m, path); } if (webSocket) { nettyRequest.headers().add(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET); nettyRequest.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); nettyRequest.headers().add("Origin", "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort())); nettyRequest.headers().add(WEBSOCKET_KEY, WebSocketUtil.getKey()); nettyRequest.headers().add("Sec-WebSocket-Version", "13"); } if (host != null) { if (uri.getPort() == -1) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else if (request.getVirtualHost() != null) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else { nettyRequest.headers().set(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } } else { host = "127.0.0.1"; } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.headers().add(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } else { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) { nettyRequest.headers().add(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0)); } } Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { String domain = realm.getNtlmDomain(); if (proxyServer != null && proxyServer.getNtlmDomain() != null) { domain = proxyServer.getNtlmDomain(); } String authHost = realm.getNtlmHost(); if (proxyServer != null && proxyServer.getHost() != null) { host = proxyServer.getHost(); } switch (realm.getAuthScheme()) { case BASIC: nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (isNonEmpty(realm.getNonce())) { try { nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; case NTLM: try { String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost); nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } break; case KERBEROS: case SPNEGO: String challengeHeader = null; String server = proxyServer == null ? host : proxyServer.getHost(); try { challengeHeader = getSpnegoEngine().generateToken(server); } catch (Throwable e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader); break; case NONE: break; default: throw new IllegalStateException("Invalid Authentication " + realm); } } if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) { nettyRequest.headers().set(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer != null) { if (!request.getHeaders().containsKey("Proxy-Connection")) { nettyRequest.headers().set("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer.getPrincipal() != null) { if (isNonEmpty(proxyServer.getNtlmDomain())) { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) { try { String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost()); nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } } // Add default accept headers. if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*"); } if (request.getHeaders().getFirstValue("User-Agent") != null) { nettyRequest.headers().set("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { nettyRequest.headers().set("User-Agent", config.getUserAgent()); } else { nettyRequest.headers().set("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config)); } if (!m.equals(HttpMethod.CONNECT)) { if (isNonEmpty(request.getCookies())) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getMethod(); if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) { String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); // We already have processed the body. if (buffer != null && buffer.writerIndex() != 0) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex()); nettyRequest.setContent(buffer); } else if (request.getByteData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getStringData().getBytes(bodyCharset))); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(Unpooled.wrappedBuffer(bytes, 0, length)); } else if (isNonEmpty(request.getParams())) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(Unpooled.wrappedBuffer(sb.toString().getBytes(bodyCharset))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = AsyncHttpProviderUtils .createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); /** * TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements. */ if (isSecure(uri)) { ByteBuf b = Unpooled.buffer(lenght); mre.writeRequest(new ByteBufOutputStream(b)); nettyRequest.setContent(b); } } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ByteBuf b = Unpooled.buffer(lenght); request.getEntityWriter().writeEntity(new ByteBufOutputStream(b)); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format("File %s is not a file or doesn't exist", file.getAbsolutePath())); } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length()); } } } return nettyRequest; }
From source file:com.nitesh.netty.snoop.client.HttpSnoopClient.java
License:Apache License
private void sendRequest() { // Prepare the HTTP request. FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());/*from www .jav a2s .com*/ //HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { System.out.println("Request sent. Success? " + future.isSuccess()); if (!future.isSuccess()) { future.cause().printStackTrace(System.out); } } }); }
From source file:com.phei.netty.nio.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).//from w w w .ja v a 2s . co m * * @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(HttpHeaderNames.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entriesConverted(); channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:com.sample.HelloWorldWithUnity3d.PingVerticle.java
License:Apache License
void startHttpServer() { HttpServer server = vertx.createHttpServer(); RouteMatcher routeMatcher = new RouteMatcher(); routeMatcher.get("/", new Handler<HttpServerRequest>() { public void handle(HttpServerRequest req) { req.response().headers().set("Content-Type", "text/html; charset=UTF-8"); System.out.println("Hello World!"); TestReq fooBarMessage = new TestReq(); fooBarMessage.key = 123456789; fooBarMessage.value = "abc"; ByteArrayOutputStream outStream = new ByteArrayOutputStream(256); TProtocol tProtocol = new TBinaryProtocol(new TIOStreamTransport(null, outStream)); try { fooBarMessage.write(tProtocol); } catch (TException e1) { // TODO Auto-generated catch block e1.printStackTrace();// w w w . j a va 2 s . c o m } byte[] content = outStream.toByteArray(); tProtocol = new TBinaryProtocol(new TIOStreamTransport(new ByteArrayInputStream(content), null)); TestReq fooBarMessage2 = new TestReq(); try { fooBarMessage2.read(tProtocol); } catch (TException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { // Session session = HibernateUtil.getCurrentSession(); MyTestTable entity = (MyTestTable) session.get(MyTestTable.class, 1); entity.setName("bbb"); Transaction tx = session.beginTransaction(); session.update(entity); tx.commit(); req.response().end("Hello World " + entity.getName()); } catch (HibernateException e) { e.printStackTrace(); } finally { // HibernateUtil.closeSession(); } } }); routeMatcher.get("/login", new Handler<HttpServerRequest>() { public void handle(HttpServerRequest req) { try { String sid = GetSessionId(req); if (sid == null) { req.response().headers().set("Set-Cookie", ServerCookieEncoder.encode(new DefaultCookie("sessionId", generateSessionId()))); } KeyPair keyPair = RSA.CreateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); RSAPublicKeySpec publicSpec = RSA.GetPublicKeySpec(keyPair); byte[] publicKeyModulus = publicSpec.getModulus().toByteArray(); byte[] publicKeyExponent = publicSpec.getPublicExponent().toByteArray(); // test byte[] encryptedData = RSA.Encrypt(publicKey, "haha!"); String decryptedText = RSA.DecryptToString(privateKey, encryptedData); JsonObject json = new JsonObject(); json.putBinary("publicKeyModulus", publicKeyModulus); json.putBinary("publicKeyExponent", publicKeyExponent); UserSession userSession = new UserSession(); userSession.privateKey = privateKey; vertx.sharedData().getMap("1").put("userSession", userSession); req.response().end(json.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); routeMatcher.post("/hello", new Handler<HttpServerRequest>() { public void handle(final HttpServerRequest req) { String sid = GetSessionId(req); req.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { String contentType = req.headers().get("Content-Type"); if ("application/octet-stream".equals(contentType)) { /* QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false); Map<String, List<String>> params = qsd.parameters(); System.out.println(params); */ UserSession userSession = (UserSession) vertx.sharedData().getMap("1") .get("userSession"); try { String decryptedText = RSA.DecryptToString(userSession.privateKey, buff.getBytes()); JsonObject json = new JsonObject(); json.putString("decryptedText", decryptedText); req.response().end(json.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } }); routeMatcher.post("/name/:name", new Handler<HttpServerRequest>() { public void handle(final HttpServerRequest req) { req.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false); Map<String, List<String>> params = qsd.parameters(); System.out.println(params); req.response().end("Your name is " + req.params().get("name")); } }); } }); routeMatcher.put("/age/:age", new Handler<HttpServerRequest>() { public void handle(final HttpServerRequest req) { req.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false); Map<String, List<String>> params = qsd.parameters(); System.out.println(params); if (params.size() > 0) req.response() .end("Your age is " + req.params().get("age") + params.get("name").get(0)); else req.response().end("Your age is " + req.params().get("age")); } }); } }); routeMatcher.get("/json", new Handler<HttpServerRequest>() { public void handle(HttpServerRequest req) { JsonObject obj = new JsonObject().putString("name", "chope"); req.response().end(obj.encode()); } }); server.requestHandler(routeMatcher).listen(808, "localhost"); }
From source file:com.springapp.mvc.netty.example.http.snoop.HttpSnoopClient.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;//www . 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) { 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(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 .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:com.springapp.mvc.netty.example.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).//from ww w . j a va 2 s .c o m * * @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(HttpHeaders.Names.HOST, host); headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE); headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaders.Names.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(HttpHeaders.Names.COOKIE, ClientCookieEncoder.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:com.topsec.bdc.platform.api.test.http.snoop.HttpSnoopClient.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 w w. j av a 2 s . c o 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) { 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(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 .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(); } }