List of usage examples for io.netty.handler.codec.http HttpHeaderNames COOKIE
AsciiString COOKIE
To view the source code for io.netty.handler.codec.http HttpHeaderNames COOKIE.
Click Source Link
From source file:ccwihr.client.t1.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). * * @return the list of headers that will be used in every example after **//*from w ww . j ava2 s. c om*/ 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(); }
From source file:cn.wcl.test.netty.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. jav a2 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(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(); }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
/** * @return request cookies (or empty Map if cookies aren't present) *///ww w.j a v a 2 s.c o m public Map<String, String> cookies() { Map<String, String> result = new HashMap<>(); String cookieString = fullHttpRequest.headers().get(HttpHeaderNames.COOKIE); Set<Cookie> cookieSet = null; if (cookieString != null) { cookieSet = ServerCookieDecoder.LAX.decode(cookieString); } if (cookieSet != null && !cookieSet.isEmpty()) { for (Cookie cookie : cookieSet) { result.put(cookie.name(), cookie.value()); } } // Cookie[] cookies = fullHttpRequest.getCookies(); // if (cookies != null) { // for (Cookie cookie : cookies) { // result.put(cookie.name(), cookie.value()); // } // } return result; }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
/** * Gets cookie by name./*from w w w. j a va 2s . c o m*/ * * @param name name of the cookie * @return cookie value or null if the cookie was not found */ public String cookie(String name) { String cookieString = fullHttpRequest.headers().get(HttpHeaderNames.COOKIE); Set<Cookie> cookieSet = null; if (cookieString != null) { cookieSet = ServerCookieDecoder.LAX.decode(cookieString); } if (cookieSet != null && !cookieSet.isEmpty()) { for (Cookie cookie : cookieSet) { if (cookie.name().equals(name)) { return cookie.value(); } } } return null; }
From source file:com.bay1ts.bay.core.Response.java
License:Apache License
/** * Adds cookie to the response. Can be invoked multiple times to insert more than one cookie. * * @param path path of the cookie/*from www .j a v a 2 s . co m*/ * @param name name of the cookie * @param value value of the cookie * @param maxAge max age of the cookie in seconds (negative for the not persistent cookie, zero - deletes the cookie) * @param secured if true : cookie will be secured * @param httpOnly if true: cookie will be marked as http only */ public void cookie(String path, String name, String value, int maxAge, boolean secured, boolean httpOnly) { Cookie cookie = new DefaultCookie(name, value); cookie.setPath(path); cookie.setMaxAge(maxAge); cookie.setSecure(secured); cookie.setHttpOnly(httpOnly); response.headers().set(HttpHeaderNames.COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); }
From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { this.httprequest = (HttpRequest) msg; requestBuilder = new Request.Builder(); requestBuilder.requestMethod(RequestMethod.valueOf(httprequest.method().name())).uri(httprequest.uri()); try {//from w w w .j av a2 s . c om // Decode URI GET query parameters QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httprequest.uri()); requestBuilder.path(queryStringDecoder.path()).query(queryStringDecoder.parameters()); // Process cookies List<Cookie> cookies = new ArrayList<>(); String cookieString = httprequest.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { ServerCookieDecoder.STRICT.decode(cookieString).stream().forEach((cookie) -> { cookies.add(NettyCookieConverter.convertToFuga(cookie)); }); } requestBuilder.cookies(cookies); // Process headers Map<String, String> headers = new HashMap<>(); httprequest.headers().entries().stream().forEach((e) -> { headers.put(e.getKey(), e.getValue()); }); requestBuilder.headers(headers); // Get real parameters from frontend HTTP server boolean isSecure = false; SocketAddress remoteAddress = ctx.channel().remoteAddress(); if (forwarded == 1) { // RFC7239 if (headers.containsKey("Forwarded")) { String fwdStr = headers.get("Forwarded"); List<String> fwdparams = Stream.of(fwdStr.split("; ")).map((s) -> s.trim()) .collect(Collectors.toList()); for (String f : fwdparams) { String p[] = f.split("="); switch (p[0]) { case "for": remoteAddress = parseAddress(p[1]); break; case "proto": isSecure = p[1].equals("https"); break; } } } } else if (forwarded == 0) { // X-Forwarded if (headers.containsKey("X-Forwarded-Proto")) { if (headers.get("X-Forwarded-Proto").equalsIgnoreCase("https")) { isSecure = true; } } if (headers.containsKey("X-Forwarded-For")) { String fwdfor = headers.get("X-Forwarded-For"); remoteAddress = parseAddress( fwdfor.contains(",") ? fwdfor.substring(0, fwdfor.indexOf(',')) : fwdfor); } else if (headers.containsKey("X-Real-IP")) { remoteAddress = parseAddress(headers.get("X-Real-IP")); } } requestBuilder.remoteAddress(remoteAddress).isSecure(isSecure); if (headers.containsKey("Accept-Language")) { String acceptLanguage = headers.get("Accept-Language"); List<Locale> acceptLocales = Stream.of(acceptLanguage.split(",")) .map((s) -> s.contains(";") ? s.substring(0, s.indexOf(";")).trim() : s.trim()) .map((s) -> s.contains("-") ? new Locale(s.split("-")[0], s.split("-")[0]) : new Locale(s)) .collect(Collectors.toList()); requestBuilder.acceptLocales(acceptLocales); } // if (httprequest.method().equals(HttpMethod.GET)) { processResponse(ctx); return; } decoder = true; } catch (Exception e) { processClientError(ctx, requestBuilder.build(), 400); return; } } if (msg instanceof HttpContent && decoder) { HttpContent httpContent = (HttpContent) msg; contentBuffer.writeBytes(httpContent.content()); if (httpContent instanceof LastHttpContent) { requestBuilder.content(new BufferedContent(contentBuffer.nioBuffer())); processResponse(ctx); } } }
From source file:com.cmz.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;// w w w.ja va 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(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(); } }
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.isKeepAlive(request); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); }//w ww .j a v a 2s .c om // Encode the cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
From source file:com.cmz.http.upload.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);// w w w . j a va 2 s.com return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:com.cmz.http.upload.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);//from w w w .j a va2s.c o m // Decide whether to close the connection or not. boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }