List of usage examples for io.netty.handler.codec.http DefaultCookie DefaultCookie
public DefaultCookie(String name, String value)
From source file: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 a va 2 s . 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 { // Start the connection attempt. // 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; try { uriGet = new URI(encoder.toString()); } catch (URISyntaxException e) { logger.log(Level.WARNING, "Error: ", e); return null; } FullHttpRequest request = new DefaultFullHttpRequest(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"); 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.write(request).sync(); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:com.barchart.http.server.PooledServerResponse.java
License:BSD License
@Override public void setCookie(final String name, final String value) { cookies.add(new DefaultCookie(name, value)); }
From source file:com.chiorichan.http.CookieDecoder.java
License:Mozilla Public License
/** * Decodes the specified Set-Cookie HTTP header value into a {@link Cookie}. * * @return the decoded {@link Cookie}//from www . j a v a2 s . co m */ public static Set<Cookie> decode(String header) { if (header == null) throw new NullPointerException("header"); final int headerLen = header.length(); if (headerLen == 0) return Collections.emptySet(); Set<Cookie> cookies = new TreeSet<Cookie>(); int i = 0; boolean rfc2965Style = false; if (header.regionMatches(true, 0, "$Version", 0, 8)) { // RFC 2965 style cookie, move to after version value i = header.indexOf(';') + 1; rfc2965Style = true; } loop: for (;;) { // Skip spaces and separators. for (;;) { if (i == headerLen) break loop; char c = header.charAt(i); if (c == '\t' || c == '\n' || c == 0x0b || c == '\f' || c == '\r' || c == ' ' || c == ',' || c == ';') { i++; continue; } break; } int newNameStart = i; int newNameEnd = i; String value; if (i == headerLen) value = null; else keyValLoop: for (;;) { char curChar = header.charAt(i); if (curChar == ';') { // NAME; (no value till ';') newNameEnd = i; value = null; break keyValLoop; } else if (curChar == '=') { // NAME=VALUE newNameEnd = i; i++; if (i == headerLen) { // NAME= (empty value, i.e. nothing after '=') value = ""; break keyValLoop; } int newValueStart = i; char c = header.charAt(i); if (c == '"') { // NAME="VALUE" StringBuilder newValueBuf = InternalThreadLocalMap.get().stringBuilder(); final char q = c; boolean hadBackslash = false; i++; for (;;) { if (i == headerLen) { value = newValueBuf.toString(); break keyValLoop; } if (hadBackslash) { hadBackslash = false; c = header.charAt(i++); if (c == '\\' || c == '"') // Escape last backslash. newValueBuf.setCharAt(newValueBuf.length() - 1, c); else // Do not escape last backslash. newValueBuf.append(c); } else { c = header.charAt(i++); if (c == q) { value = newValueBuf.toString(); break keyValLoop; } newValueBuf.append(c); if (c == '\\') hadBackslash = true; } } } else { // NAME=VALUE; int semiPos = header.indexOf(';', i); if (semiPos > 0) { value = header.substring(newValueStart, semiPos); i = semiPos; } else { value = header.substring(newValueStart); i = headerLen; } } break keyValLoop; } else i++; if (i == headerLen) { // NAME (no value till the end of string) newNameEnd = headerLen; value = null; break; } } if (!rfc2965Style || (!header.regionMatches(newNameStart, "$Path", 0, "$Path".length()) && !header.regionMatches(newNameStart, "$Domain", 0, "$Domain".length()) && !header.regionMatches(newNameStart, "$Port", 0, "$Port".length()))) { // skip obsolete RFC2965 fields String name = header.substring(newNameStart, newNameEnd); cookies.add(new DefaultCookie(name, value)); } } return cookies; }
From source file:com.dwarf.netty.guide.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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } 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 .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.ejisto.modules.vertx.handler.SecurityEnforcer.java
License:Open Source License
@Override public void handle(HttpServerRequest request) { final MultiMap headers = request.headers(); Optional<String> xRequestedWith = Optional.ofNullable(headers.get(X_REQUESTED_WITH)) .filter("XMLHttpRequest"::equals); if (xRequestedWith.isPresent()) { if (!isDevModeActive()) { request.response().write(SECURITY_TOKEN); }// w w w . j av a 2 s . com Optional<String> header = Optional.ofNullable(headers.get(XSRF_TOKEN_HEADER)).filter(token::equals); if (!header.isPresent()) { Boilerplate.writeError(request, HttpResponseStatus.FORBIDDEN.code(), HttpResponseStatus.FORBIDDEN.reasonPhrase()); return; } } if ("/index.html".equals(request.path())) { Cookie cookie = new DefaultCookie(XSRF_TOKEN, token); cookie.setPath("/"); request.response().headers().set(HttpHeaders.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } super.handle(request); }
From source file:com.ejisto.modules.vertx.handler.SecurityEnforcerTest.java
License:Open Source License
@Test public void testTokenCreation() throws Exception { MultiMap headers = new CaseInsensitiveMultiMap(); when(serverRequest.path()).thenReturn("/index.html"); when(serverResponse.headers()).thenReturn(headers); System.setProperty(StringConstants.DEV_MODE.getValue(), "true"); enforcer.handle(serverRequest);// w ww . j a va 2s.c o m verify(serverResponse, never()).write(SecurityEnforcer.SECURITY_TOKEN); assertTrue(headers.contains(HttpHeaders.SET_COOKIE)); assertNotNull(headers.get(HttpHeaders.SET_COOKIE)); Cookie cookie = new DefaultCookie(SecurityEnforcer.XSRF_TOKEN, NSA_PROOF_TOKEN); cookie.setPath("/"); assertEquals(ServerCookieEncoder.encode(cookie), headers.get(HttpHeaders.SET_COOKIE)); }
From source file:com.github.ambry.rest.NettyRequestTest.java
License:Open Source License
/** * Tests conversion of {@link HttpRequest} to {@link NettyRequest} given good input. * @throws RestServiceException/*from www. j a v a2s . c o m*/ */ @Test public void conversionWithGoodInputTest() throws RestServiceException { // headers HttpHeaders headers = new DefaultHttpHeaders(false); headers.add(HttpHeaders.Names.CONTENT_LENGTH, new Random().nextInt(Integer.MAX_VALUE)); headers.add("headerKey", "headerValue1"); headers.add("headerKey", "headerValue2"); headers.add("overLoadedKey", "headerOverloadedValue"); headers.add("paramNoValueInUriButValueInHeader", "paramValueInHeader"); headers.add("headerNoValue", (Object) null); headers.add("headerNoValueButValueInUri", (Object) null); // params Map<String, List<String>> params = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(2); values.add("paramValue1"); values.add("paramValue2"); params.put("paramKey", values); values = new ArrayList<String>(1); values.add("paramOverloadedValue"); params.put("overLoadedKey", values); values = new ArrayList<String>(1); values.add("headerValueInUri"); params.put("headerNoValueButValueInUri", values); params.put("paramNoValue", null); params.put("paramNoValueInUriButValueInHeader", null); StringBuilder uriAttachmentBuilder = new StringBuilder("?"); for (Map.Entry<String, List<String>> param : params.entrySet()) { if (param.getValue() != null) { for (String value : param.getValue()) { uriAttachmentBuilder.append(param.getKey()).append("=").append(value).append("&"); } } else { uriAttachmentBuilder.append(param.getKey()).append("&"); } } uriAttachmentBuilder.deleteCharAt(uriAttachmentBuilder.length() - 1); String uriAttachment = uriAttachmentBuilder.toString(); NettyRequest nettyRequest; String uri; Set<Cookie> cookies = new HashSet<Cookie>(); Cookie httpCookie = new DefaultCookie("CookieKey1", "CookieValue1"); cookies.add(httpCookie); httpCookie = new DefaultCookie("CookieKey2", "CookieValue2"); cookies.add(httpCookie); headers.add(RestUtils.Headers.COOKIE, getCookiesHeaderValue(cookies)); uri = "/GET" + uriAttachment; nettyRequest = createNettyRequest(HttpMethod.GET, uri, headers); validateRequest(nettyRequest, RestMethod.GET, uri, headers, params, cookies); closeRequestAndValidate(nettyRequest); uri = "/POST" + uriAttachment; nettyRequest = createNettyRequest(HttpMethod.POST, uri, headers); validateRequest(nettyRequest, RestMethod.POST, uri, headers, params, cookies); closeRequestAndValidate(nettyRequest); uri = "/DELETE" + uriAttachment; nettyRequest = createNettyRequest(HttpMethod.DELETE, uri, headers); validateRequest(nettyRequest, RestMethod.DELETE, uri, headers, params, cookies); closeRequestAndValidate(nettyRequest); uri = "/HEAD" + uriAttachment; nettyRequest = createNettyRequest(HttpMethod.HEAD, uri, headers); validateRequest(nettyRequest, RestMethod.HEAD, uri, headers, params, cookies); closeRequestAndValidate(nettyRequest); }
From source file:com.gw.services.client.HttpsClient.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 . ja v 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 = CLIENT_CONTEXT; } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpsClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); String requestBody = "{\"productId\": 11,\"userName\": \"caiwei\",\"amount\": 1000}"; ByteBuf content = Unpooled.copiedBuffer(requestBody.getBytes(CharsetUtil.UTF_8)); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), content); 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); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); // 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.lunex.inputprocessor.testdemo.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;//w w w . j a v a2 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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } 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.POST, 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"))); String json = "{\"foo\":\"bar\"}"; request.headers().set("json", json); // 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.mastfrog.acteur.wicket.adapters.CookieConverter.java
License:Open Source License
@Override public Cookie unconvert(javax.servlet.http.Cookie t) { if (t instanceof CookieAdapter) { return ((CookieAdapter) t).cookie; } else {//ww w .j a v a2 s. com DefaultCookie dc = new DefaultCookie(t.getName(), t.getValue()); dc.setComment(t.getComment()); dc.setMaxAge(t.getMaxAge()); dc.setDomain(t.getDomain()); dc.setVersion(t.getVersion()); return dc; } }