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:edumsg.netty.EduMsgNettyServerInitializer.java
License:Open Source License
@Override protected void initChannel(SocketChannel arg0) { CorsConfig corsConfig = CorsConfig.withAnyOrigin() .allowedRequestHeaders("X-Requested-With", "Content-Type", "Content-Length") .allowedRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.OPTIONS)// w w w. java 2 s. com .build(); ChannelPipeline p = arg0.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(arg0.alloc())); } p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast(new CorsHandler(corsConfig)); p.addLast(new EduMsgNettyServerHandler()); }
From source file:etcd.client.HttpClientTest.java
License:Open Source License
@Test public void httpClient() throws Exception { final ServerList serverList = new ServerList(); serverList.addServer(URI.create("http://localhost:2001"), true); final HttpClient httpClient = new HttpClient(new NioEventLoopGroup(), Runnable::run, serverList, false); final CountDownLatch latch = new CountDownLatch(1); httpClient.send(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v2/keys/"), (response) -> {//from w w w .j ava 2 s .com final DefaultFullHttpResponse httpResponse = response.getHttpResponse(); final ByteBuf contentBuffer = httpResponse.content(); System.out.println(contentBuffer.toString(Charset.defaultCharset())); latch.countDown(); }); assertTrue(latch.await(500, TimeUnit.MILLISECONDS), "Failed to get valid response from server."); }
From source file: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 ? "example/http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("example/http".equalsIgnoreCase(scheme)) { port = 80;//from w w w. ja v a 2s . c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"example/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:example.http2.helloworld.server.HelloWorldHttp2Handler.java
License:Apache License
private static Http2Headers http1HeadersToHttp2Headers(FullHttpRequest request) { CharSequence host = request.headers().get(HttpHeaderNames.HOST); Http2Headers http2Headers = new DefaultHttp2Headers().method(HttpMethod.GET.asciiName()).path(request.uri()) .scheme(HttpScheme.HTTP.name()); if (host != null) { http2Headers.authority(host);//from ww w. j av a 2 s . co m } return http2Headers; }
From source file:freddo.dtalk2.broker.netty.NettyBrokerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { LOG.trace(">>> handleHttpRequest: {}", req.getUri()); if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;// w ww.j ava 2 s . c om } if (req.getMethod() == HttpMethod.GET && req.getUri().startsWith(DTalk.DTALKSRV_PATH)) { // // DTalk WebSocket Handshake // WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, true); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); synchronized (mChannelMapper) { NettyChannel channel = new NettyChannel(ctx, handshaker); channel.setIdleTime(60); mChannelMapper.put(ctx, channel); } } } else { // // HTTP Request // } }
From source file:godfinger.http.HttpServerInitializer.java
License:Apache License
@Override public void initChannel(SocketChannel channel) { CorsConfig corsConfig = CorsConfig.withAnyOrigin().allowCredentials() .allowedRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE) .allowedRequestHeaders("accept", "content-type", "session-id").build(); ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new FaviconHandler()); pipeline.addLast(new CorsHandler(corsConfig)); pipeline.addLast(new HttpObjectAggregator(1024 * 1024)); pipeline.addLast(new HttpRequestHandler(requestProcessor)); }
From source file:gribbit.http.request.Request.java
License:Open Source License
public Request(ChannelHandlerContext ctx, HttpRequest httpReq) throws ResponseException { this.reqReceivedTimeEpochMillis = System.currentTimeMillis(); this.httpRequest = httpReq; HttpHeaders headers = httpReq.headers(); // Netty changes the URI of the request to "/bad-request" if the HTTP request was malformed this.rawURL = httpReq.uri(); if (rawURL.equals("/bad-request")) { throw new BadRequestException(); } else if (rawURL.isEmpty()) { rawURL = "/"; }/*from www. j ava2s .co m*/ // Decode the URL RequestURL requestURL = new RequestURL(rawURL); this.normalizedURL = requestURL.getNormalizedPath(); this.queryParamToVals = requestURL.getQueryParams(); // TODO: figure out how to detect HTTP/2 connections this.httpVersion = httpReq.protocolVersion().toString(); // Get HTTP2 stream ID this.streamId = headers.getAsString(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); this.isSecure = ctx.pipeline().get(SslHandler.class) != null; // TODO: is this correct for HTTP2? // Decode cookies try { for (CharSequence cookieHeader : headers.getAll(COOKIE)) { for (Cookie cookie : ServerCookieDecoder.STRICT.decode(cookieHeader.toString())) { // Log.fine("Cookie in request: " + nettyCookie); if (cookieNameToCookies == null) { cookieNameToCookies = new HashMap<>(); } String cookieName = cookie.name(); // Multiple cookies may be present in the request with the same name but with different paths ArrayList<Cookie> cookiesWithThisName = cookieNameToCookies.get(cookieName); if (cookiesWithThisName == null) { cookieNameToCookies.put(cookieName, cookiesWithThisName = new ArrayList<>()); } cookiesWithThisName.add(cookie); } } } catch (IllegalArgumentException e) { // Malformed cookies cause ServerCookieDecoder to throw IllegalArgumentException // Log.info("Malformed cookie in request"); throw new BadRequestException(); } // Sort cookies into decreasing order of path length, in case client doesn't conform to RFC6295, // delivering the cookies in this order itself. This allows us to get the most likely single // cookie for a given cookie name by reading the first cookie in a list for a given name. if (cookieNameToCookies != null) { for (Entry<String, ArrayList<Cookie>> ent : cookieNameToCookies.entrySet()) { Collections.sort(ent.getValue(), COOKIE_COMPARATOR); } } this.method = httpReq.method(); // Force the GET method if HEAD is requested this.isHEADRequest = this.method == HttpMethod.HEAD; if (this.isHEADRequest) { this.method = HttpMethod.GET; } this.isKeepAlive = HttpUtil.isKeepAlive(httpReq) && httpReq.protocolVersion().equals(HttpVersion.HTTP_1_0); CharSequence host = headers.get(HOST); this.host = host == null ? null : host.toString(); this.xRequestedWith = headers.get("X-Requested-With"); this.accept = headers.get(ACCEPT); this.acceptCharset = headers.get(ACCEPT_CHARSET); this.acceptLanguage = headers.get(ACCEPT_LANGUAGE); this.origin = headers.get(ORIGIN); this.referer = headers.get(REFERER); this.userAgent = headers.get(USER_AGENT); InetSocketAddress requestorSocketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); if (requestorSocketAddr != null) { InetAddress address = requestorSocketAddr.getAddress(); if (address != null) { this.requestor = address.getHostAddress(); } } CharSequence acceptEncoding = headers.get(ACCEPT_ENCODING); this.acceptEncodingGzip = acceptEncoding != null && acceptEncoding.toString().toLowerCase().contains("gzip"); this.ifModifiedSince = headers.get(IF_MODIFIED_SINCE); if (this.ifModifiedSince != null && this.ifModifiedSince.length() > 0) { this.ifModifiedSinceEpochSecond = ZonedDateTime .parse(this.ifModifiedSince, DateTimeFormatter.RFC_1123_DATE_TIME).toEpochSecond(); } // // If this is a hash URL, look up original URL whose served resource was hashed to give this hash URL. // // We only need to serve the resource at a hash URL once per resource per client, since resources served // // from hash URLs are indefinitely cached in the browser. // // TODO: Move cache-busting out of http package // this.urlHashKey = CacheExtension.getHashKey(this.urlPath); // this.urlPathUnhashed = this.urlHashKey != null ? CacheExtension.getOrigURL(this.urlPath) : this.urlPath; // // Get flash messages from cookie, if any // this.flashMessages = FlashMessage.fromCookieString(getCookieValue(Cookie.FLASH_COOKIE_NAME)); }
From source file:holon.internal.http.netty.HttpUploadServerHandlerTempl.java
License:Open Source 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.getUri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);//w ww.ja v a 2 s. co 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 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(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\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 (request.getMethod().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 = 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(); } } } else { writeResponse(ctx.channel()); } }
From source file:holon.internal.http.netty.NettyServerHandler.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (request.getMethod().equals(HttpMethod.GET)) { // No more work to do here, we will get a follow-up message which will trigger the else branch // at the bottom of this method. return; }//from ww w . jav a 2 s . c om try { formParams = new HashMap<>(); decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); ctx.channel().close(); return; } } // 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(); ctx.channel().close(); return; } // example of reading chunk by chunk (minimize memory usage due to Factory) readFormUploadChunked(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { ringBuffer.publishEvent(NettyServerHandler::translate, request, ctx.channel(), formParams); reset(); } } } else { ringBuffer.publishEvent(NettyServerHandler::translate, request, ctx.channel(), formParams); } }
From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java
License:Open Source License
@Override public HttpClientRequest get(int port, String host, String requestURI) { return request(io.advantageous.conekt.http.HttpMethod.GET, port, host, requestURI); }