List of usage examples for io.netty.handler.codec.http HttpRequest getProtocolVersion
@Deprecated HttpVersion getProtocolVersion();
From source file:HttpUploadServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.getUri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);//from w ww .j ava2 s.c o m return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod List<Entry<String, String>> headers = request.headers().entries(); for (Entry<String, String> entry : 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(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie.toString() + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri()); 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 try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.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) { readHttpDataAllReceive(ctx.channel()); writeResponse(ctx.channel()); readingChunks = false; reset(); } } } }
From source file:baseFrame.netty.atest.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w w w .ja v a 2s .c o m*/ boolean keepAlive = HttpHeaders.isKeepAlive(request); // Encode the cookie. String cookieString = request.headers().get(Names.COOKIE); if (cookieString != null) { Set<Cookie> cookies = CookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } } else { // Browser sent no cookie. Add some. /* response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));*/ } if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } responseContent.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); //responseContent.append("HOSTNAME: ").append(request.headers().).append("\r\n"); responseContent.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Entry<String, String> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); responseContent.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } responseContent.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { responseContent.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } responseContent.append("\r\n"); } response = setResponse(response, responseContent); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; if (msg instanceof LastHttpContent) { } } }
From source file:cc.io.lessons.server.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { System.out.println(msg.toString()); } else {/*www .ja v a 2 s . co m*/ System.out.println(ByteBufUtil.hexDump(((HttpContent) msg).content())); //System.out.println(((HttpContent) msg).content().toString(Charset.defaultCharset())); } if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.getUri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod List<Entry<String, String>> headers = request.headers().entries(); for (Entry<String, String> entry : 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(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie.toString() + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri()); 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 try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.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(); } } } }
From source file:com.bala.learning.learning.netty.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/*www.j a va 2s . c o m*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.chenyang.proxy.http.HttpSchemaHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; String originalHost = HostNamePortUtil.getHostName(httpRequest); int originalPort = HostNamePortUtil.getPort(httpRequest); HttpRemote apnProxyRemote = new HttpRemote(originalHost, originalPort); if (!HostAuthenticationUtil.isValidAddress(apnProxyRemote.getInetSocketAddress())) { HttpErrorUtil.writeAndFlush(uaChannelCtx.channel(), HttpResponseStatus.FORBIDDEN); return; }//from www. ja va 2 s. co m Channel uaChannel = uaChannelCtx.channel(); HttpConnectionAttribute apnProxyConnectionAttribute = HttpConnectionAttribute.build( uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(), httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote); uaChannelCtx.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) != null) { uaChannelCtx.pipeline().remove(HttpUserAgentForwardHandler.HANDLER_NAME); } if (uaChannelCtx.pipeline().get(HttpUserAgentTunnelHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentTunnelHandler.HANDLER_NAME, new HttpUserAgentTunnelHandler()); } } else { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentForwardHandler.HANDLER_NAME, new HttpUserAgentForwardHandler()); } } } uaChannelCtx.fireChannelRead(msg); }
From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java
License:Apache License
private HttpRequest constructRequestForProxy(HttpRequest httpRequest, HttpRemote apnProxyRemote) { String uri = httpRequest.getUri(); uri = this.getPartialUrl(uri); HttpRequest _httpRequest = new DefaultHttpRequest(httpRequest.getProtocolVersion(), httpRequest.getMethod(), uri);/*from ww w . j a v a2s . c o m*/ Set<String> headerNames = httpRequest.headers().names(); for (String headerName : headerNames) { if (StringUtils.equalsIgnoreCase(headerName, "Proxy-Connection")) { _httpRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { _httpRequest.headers().add(headerName, httpRequest.headers().getAll(headerName)); } } Iterator<Entry<String, String>> iterator = _httpRequest.headers().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); logger.info(" heard : {} {}", entry.getKey(), entry.getValue()); } return _httpRequest; }
From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java
License:Apache License
@Test public void shouldEncodeBucketConfigRequest() throws Exception { BucketConfigRequest request = new BucketConfigRequest("/path/", InetAddress.getLocalHost(), "bucket", "password"); channel.writeOutbound(request);/*www. ja v a 2s . c om*/ HttpRequest outbound = (HttpRequest) channel.readOutbound(); assertEquals(HttpMethod.GET, outbound.getMethod()); assertEquals(HttpVersion.HTTP_1_1, outbound.getProtocolVersion()); assertEquals("/path/bucket", outbound.getUri()); assertTrue(outbound.headers().contains(HttpHeaders.Names.AUTHORIZATION)); assertTrue(outbound.headers().contains(HttpHeaders.Names.HOST)); assertEquals("Basic YnVja2V0OnBhc3N3b3Jk", outbound.headers().get(HttpHeaders.Names.AUTHORIZATION)); assertEquals("Couchbase Client Mock", outbound.headers().get(HttpHeaders.Names.USER_AGENT)); }
From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java
License:Apache License
@Test public void shouldEncodeFlushRequest() { FlushRequest request = new FlushRequest("bucket", "password"); channel.writeOutbound(request);/*from w ww. j a v a 2 s . co m*/ HttpRequest outbound = (HttpRequest) channel.readOutbound(); assertEquals(HttpMethod.POST, outbound.getMethod()); assertEquals(HttpVersion.HTTP_1_1, outbound.getProtocolVersion()); assertEquals("/pools/default/buckets/bucket/controller/doFlush", outbound.getUri()); assertTrue(outbound.headers().contains(HttpHeaders.Names.AUTHORIZATION)); assertTrue(outbound.headers().contains(HttpHeaders.Names.HOST)); assertEquals("Basic YnVja2V0OnBhc3N3b3Jk", outbound.headers().get(HttpHeaders.Names.AUTHORIZATION)); assertEquals("Couchbase Client Mock", outbound.headers().get(HttpHeaders.Names.USER_AGENT)); }
From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java
License:Apache License
@Test public void shouldEncodeBucketStreamingRequest() throws Exception { BucketStreamingRequest request = new BucketStreamingRequest("/path/", "bucket", "password"); channel.writeOutbound(request);//from w ww . j ava 2s . c o m HttpRequest outbound = (HttpRequest) channel.readOutbound(); assertEquals(HttpMethod.GET, outbound.getMethod()); assertEquals(HttpVersion.HTTP_1_1, outbound.getProtocolVersion()); assertEquals("/path/bucket", outbound.getUri()); assertTrue(outbound.headers().contains(HttpHeaders.Names.AUTHORIZATION)); assertEquals("Basic YnVja2V0OnBhc3N3b3Jk", outbound.headers().get(HttpHeaders.Names.AUTHORIZATION)); assertEquals("Couchbase Client Mock", outbound.headers().get(HttpHeaders.Names.USER_AGENT)); }
From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java
License:Apache License
@Test public void shouldNotBreakLinesOnLongAuth() throws Exception { String longPassword = "thisIsAveryLongPasswordWhichShouldNotContainLineBreaksAfterEncodingOtherwise" + "itWillBreakTheRequestResponseFlowWithTheServer"; BucketConfigRequest request = new BucketConfigRequest("/path/", InetAddress.getLocalHost(), "bucket", longPassword);//from w w w . j av a2 s . com channel.writeOutbound(request); HttpRequest outbound = (HttpRequest) channel.readOutbound(); assertEquals(HttpMethod.GET, outbound.getMethod()); assertEquals(HttpVersion.HTTP_1_1, outbound.getProtocolVersion()); assertEquals("/path/bucket", outbound.getUri()); assertTrue(outbound.headers().contains(HttpHeaders.Names.AUTHORIZATION)); assertNotNull(outbound.headers().get(HttpHeaders.Names.AUTHORIZATION)); assertTrue(outbound.headers().contains(HttpHeaders.Names.HOST)); assertEquals("Couchbase Client Mock", outbound.headers().get(HttpHeaders.Names.USER_AGENT)); }