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:io.higgs.ws.client.WebSocketClient.java
License:Apache License
public WebSocketClient(URI uri, Map<String, Object> customHeaders, boolean autoPong, String[] sslProtocols) { super(BUILDER, HttpRequestBuilder.group(), uri, HttpMethod.GET, HttpVersion.HTTP_1_1, new PageReader()); final String protocol = uri.getScheme(); if (!"ws".equals(protocol) && !"wss".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); }// w w w . j av a2s. c o m if (customHeaders != null) { for (Map.Entry<String, Object> e : customHeaders.entrySet()) { customHeaderSet.add(e.getKey(), e.getValue()); } } handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, version, subprotocol, allowExtensions, customHeaderSet, maxFramePayloadLength); handler = new WebSocketClientHandler(handshaker, listeners, autoPong); this.autoPong = autoPong; this.sslProtocols = sslProtocols == null || sslProtocols.length == 0 ? HttpRequestBuilder.getSupportedSSLProtocols() : sslProtocols; }
From source file:io.liveoak.container.protocols.http.HttpResourceRequestDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, DefaultHttpRequest msg, List<Object> out) throws Exception { URI uri = new URI(msg.getUri()); String query = uri.getRawQuery(); if (query == null) { query = "?"; } else {/*from w w w . j av a2s.c o m*/ query = "?" + query; } QueryStringDecoder decoder = new QueryStringDecoder(query); String path = uri.getPath(); int lastDotLoc = path.lastIndexOf('.'); String extension = null; if (lastDotLoc > 0) { extension = path.substring(lastDotLoc + 1); } String acceptHeader = msg.headers().get(HttpHeaders.Names.ACCEPT); if (acceptHeader == null) { acceptHeader = "application/json"; } MediaTypeMatcher mediaTypeMatcher = new DefaultMediaTypeMatcher(acceptHeader, extension); ResourceParams params = DefaultResourceParams.instance(decoder.parameters()); // for cases when content is preset, and bypasses HttpRequestBodyHandler ByteBuf content = null; if (msg instanceof DefaultFullHttpRequest) { content = ((DefaultFullHttpRequest) msg).content().retain(); } if (msg.getMethod().equals(HttpMethod.POST)) { String contentTypeHeader = msg.headers().get(HttpHeaders.Names.CONTENT_TYPE); MediaType contentType = new MediaType(contentTypeHeader); out.add(new DefaultResourceRequest.Builder(RequestType.CREATE, new ResourcePath(path)) .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher) .requestAttribute(HttpHeaders.Names.AUTHORIZATION, msg.headers().get(HttpHeaders.Names.AUTHORIZATION)) .requestAttribute(HttpHeaders.Names.CONTENT_TYPE, contentType) .requestAttribute(HTTP_REQUEST, msg) .resourceState(new DefaultLazyResourceState(codecManager, contentType, content)).build()); } else if (msg.getMethod().equals(HttpMethod.GET)) { out.add(new DefaultResourceRequest.Builder(RequestType.READ, new ResourcePath(path)) .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher) .requestAttribute(HttpHeaders.Names.AUTHORIZATION, msg.headers().get(HttpHeaders.Names.AUTHORIZATION)) .requestAttribute(HttpHeaders.Names.ACCEPT, new MediaType(acceptHeader)) .requestAttribute(HTTP_REQUEST, msg).pagination(decodePagination(params)) .returnFields(decodeReturnFields(params)).sorting(decodeSorting(params)).build()); } else if (msg.getMethod().equals(HttpMethod.PUT)) { String contentTypeHeader = msg.headers().get(HttpHeaders.Names.CONTENT_TYPE); MediaType contentType = new MediaType(contentTypeHeader); out.add(new DefaultResourceRequest.Builder(RequestType.UPDATE, new ResourcePath(path)) .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher) .requestAttribute(HttpHeaders.Names.AUTHORIZATION, msg.headers().get(HttpHeaders.Names.AUTHORIZATION)) .requestAttribute(HttpHeaders.Names.CONTENT_TYPE, contentType) .requestAttribute(HTTP_REQUEST, msg) .resourceState(new DefaultLazyResourceState(codecManager, contentType, content)).build()); } else if (msg.getMethod().equals(HttpMethod.DELETE)) { out.add(new DefaultResourceRequest.Builder(RequestType.DELETE, new ResourcePath(path)) .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher) .requestAttribute(HttpHeaders.Names.AUTHORIZATION, msg.headers().get(HttpHeaders.Names.AUTHORIZATION)) .requestAttribute(HttpHeaders.Names.ACCEPT, new MediaType(acceptHeader)) .requestAttribute(HTTP_REQUEST, msg).build()); } }
From source file:io.liveoak.container.protocols.http.HttpResourceRequestDecoderTest.java
License:Open Source License
@Test public void testDecodeGet() throws Exception { DefaultResourceRequest decoded = decode(HttpMethod.GET, "/memory/people/bob"); assertThat(decoded.requestType()).isEqualTo(RequestType.READ); assertThat(decoded.resourcePath().segments()).hasSize(3); assertThat(decoded.resourcePath().segments().get(0).name()).isEqualTo("memory"); assertThat(decoded.resourcePath().segments().get(1).name()).isEqualTo("people"); assertThat(decoded.resourcePath().segments().get(2).name()).isEqualTo("bob"); //assertThat(decoded.mediaType()).isEqualTo(MediaType.JSON); assertThat(decoded.requestContext().pagination()).isNotNull(); // TODO: still looking into whether this test failing is proper or not //assertThat( decoded.pagination() ).isEqualTo(Pagination.NONE); assertThat(decoded.state()).isNull(); }
From source file:io.nebo.container.ServletContentHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; log.info("uri" + request.getUri()); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false); NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, servletContext, response); servletRequest = new NettyHttpServletRequest(ctx, servletContext, request, inputStream, servletResponse);/*w w w . j a v a2s .c o m*/ if (HttpMethod.GET.equals(request.getMethod())) { HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request)); if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE), ctx.voidPromise()); } ctx.fireChannelRead(servletRequest); } else if (HttpMethod.POST.equals(request.getMethod())) { decoder = new HttpPostRequestDecoder(factory, request); } } if (decoder != null && msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; log.info("HttpContent" + chunk.content().readableBytes()); inputStream.addContent(chunk); List<InterfaceHttpData> interfaceHttpDatas = decoder.getBodyHttpDatas(); for (InterfaceHttpData data : interfaceHttpDatas) { try { if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { Attribute attribute = (Attribute) data; Map<String, String[]> params = servletRequest.getParameterMap(); HttpRequestUtils.setParamMap(attribute.getName(), attribute.getValue(), params); } } finally { // data.release(); } } } if (decoder != null && msg instanceof LastHttpContent) { ctx.fireChannelRead(servletRequest); reset(); } }
From source file:io.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;//ww 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 = 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(), Unpooled.EMPTY_BUFFER); 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:io.netty.example.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);/*from ww w .j a va 2 s . c om*/ 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 an HttpPostRequestDecoder if (HttpMethod.GET.equals(request.method())) { // GET Method: should not try to create an 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(), true); return; } boolean 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: "); } } // 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(), true); 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()); reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:io.netty.example.spdy.client.SpdyClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.SPDY_3_1, ApplicationProtocolNames.HTTP_1_1)) .build();/*ww w . j a v a 2 s . c o m*/ HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler)); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to " + HOST + ':' + PORT); // Create a GET request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "", Unpooled.EMPTY_BUFFER); request.headers().set(HttpHeaderNames.HOST, HOST); request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); // Send the GET request. channel.writeAndFlush(request).sync(); // Waits for the complete HTTP response httpResponseHandler.queue().take().sync(); System.out.println("Finished SPDY HTTP GET"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
From source file:io.reactivex.netty.contexts.http.ClientHandlerTest.java
License:Apache License
private static void sendRequestAndAssert(HandlerHolder holder) throws Exception { holder.correlator.onNewServerRequest(holder.requestId, new ContextsContainerImpl(holder.keySupplier)); try {/*w ww . ja v a2 s . co m*/ DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); holder.addSerializedContext(request, CTX_1_NAME, CTX_1_VAL, new BidirectionalTestContextSerializer()); holder.handler.write(holder.ctx, request, holder.ctx.newPromise()); Assert.assertNotNull("Context container not set after request sent.", ContextAttributeStorageHelper.getContainer(holder.ctx, holder.requestId)); ContextKeySupplier supplier = new HttpContextKeySupplier(request.headers()); ContextsContainer container = new ContextsContainerImpl(supplier); Assert.assertEquals("Context not available in the container.", CTX_1_VAL, container.getContext(CTX_1_NAME)); Assert.assertEquals("Request Id header not added.", holder.getRequestId(), request.headers().get(holder.getProvider().getRequestIdContextKeyName())); } finally { holder.correlator.onServerProcessingEnd(holder.requestId); System.err.println("Sent server processing end callback to correlator."); RxContexts.DEFAULT_CORRELATOR.dumpThreadState(System.err); } }
From source file:io.reactivex.netty.contexts.http.ServerHandlerTest.java
License:Apache License
private static void readRequestAndAssert(HandlerHolder holder) throws Exception { DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); holder.addSerializedContext(request, CTX_1_NAME, CTX_1_VAL); holder.handler.channelRead(holder.ctx, request); ContextsContainer container = ContextAttributeStorageHelper.getContainer(holder.ctx, holder.requestId); Assert.assertNotNull("Context container not set after request receive.", container); Assert.assertEquals("Context not available in the container.", CTX_1_VAL, container.getContext(CTX_1_NAME)); Assert.assertEquals("Request Id header not added.", CTX_1_VAL, container.getContext(CTX_1_NAME)); }
From source file:io.reactivex.netty.protocol.http.client.ClientRequestResponseConverter.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { Class<?> recievedMsgClass = msg.getClass(); if (HttpClientRequest.class.isAssignableFrom(recievedMsgClass)) { HttpClientRequest<?> rxRequest = (HttpClientRequest<?>) msg; MultipleFutureListener allWritesListener = new MultipleFutureListener(promise); Observable<?> contentSource = null; switch (rxRequest.getContentSourceType()) { case Raw: if (!rxRequest.getHeaders().isContentLengthSet()) { rxRequest.getHeaders().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); }//ww w. j a v a 2 s .c om contentSource = rxRequest.getRawContentSource(); break; case Typed: if (!rxRequest.getHeaders().isContentLengthSet()) { rxRequest.getHeaders().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); } contentSource = rxRequest.getContentSource(); break; case Absent: if (!rxRequest.getHeaders().isContentLengthSet() && rxRequest.getMethod() != HttpMethod.GET) { rxRequest.getHeaders().set(HttpHeaders.Names.CONTENT_LENGTH, 0); } break; } writeHttpHeaders(ctx, rxRequest, allWritesListener); // In all cases, write headers first. if (null != contentSource) { // If content present then write Last Content after all content is written. if (!rxRequest.getHeaders().isContentLengthSet()) { rxRequest.getHeaders().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); } writeContent(ctx, allWritesListener, contentSource, promise); } else { // If no content then write Last Content immediately. // In order for netty's codec to understand that HTTP request writing is over, we always have to write the // LastHttpContent irrespective of whether it is chunked or not. writeAContentChunk(ctx, allWritesListener, new DefaultLastHttpContent()); } } else { ctx.write(msg, promise); // pass through, since we do not understand this message. } }