io.netty.handler.codec.http.HttpRequest Java Examples
The following examples show how to use
io.netty.handler.codec.http.HttpRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpsHostCaptureFilter.java From browserup-proxy with Apache License 2.0 | 6 votes |
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; if (ProxyUtils.isCONNECT(httpRequest)) { Attribute<String> hostname = ctx.channel().attr(AttributeKey.valueOf(HOST_ATTRIBUTE_NAME)); String hostAndPort = httpRequest.uri(); // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example) // would be unexpected. String hostNoDefaultPort = BrowserUpHttpUtil.removeMatchingPort(hostAndPort, 443); hostname.set(hostNoDefaultPort); } } return null; }
Example #2
Source File: ModelServerTest.java From serve with Apache License 2.0 | 6 votes |
@Test( alwaysRun = true, dependsOnMethods = {"testDescribeModelNotFound"}) public void testRegisterModelMissingUrl() throws InterruptedException { Channel channel = TestUtils.connect(true, configManager); Assert.assertNotNull(channel); HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/models"); channel.writeAndFlush(req).sync(); channel.closeFuture().sync(); ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class); Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code()); Assert.assertEquals(resp.getMessage(), "Parameter url is required."); }
Example #3
Source File: DefaultRiposteProxyRouterSpanNamingAndTaggingStrategyTest.java From riposte with Apache License 2.0 | 6 votes |
@Test public void alternate_constructor_creates_instance_using_specified_wingtips_strategy_and_adapter() { // given HttpTagAndSpanNamingStrategy<HttpRequest, HttpResponse> wingtipsStrategyMock = mock(HttpTagAndSpanNamingStrategy.class); HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> wingtipsAdapterMock = mock(HttpTagAndSpanNamingAdapter.class); // when DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy instance = new DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy(wingtipsStrategyMock, wingtipsAdapterMock); // then assertThat(instance.tagAndNamingStrategy).isSameAs(wingtipsStrategyMock); assertThat(instance.tagAndNamingAdapter).isSameAs(wingtipsAdapterMock); }
Example #4
Source File: NettyResponseChannelTest.java From ambry with Apache License 2.0 | 6 votes |
/** * Checks the headers in the response match those in the request. * @param request the {@link HttpRequest} with the original value of the headers. * @param response the {@link HttpResponse} that should have the same value for some headers in {@code request}. * @throws ParseException */ private void checkHeaders(HttpRequest request, HttpResponse response) throws ParseException { assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.status()); assertEquals(HttpHeaderNames.CONTENT_TYPE + " does not match", request.headers().get(HttpHeaderNames.CONTENT_TYPE), response.headers().get(HttpHeaderNames.CONTENT_TYPE)); assertEquals(HttpHeaderNames.CONTENT_LENGTH + " does not match", request.headers().get(HttpHeaderNames.CONTENT_LENGTH), response.headers().get(HttpHeaderNames.CONTENT_LENGTH)); assertEquals(HttpHeaderNames.LOCATION + " does not match", request.headers().get(HttpHeaderNames.LOCATION), response.headers().get(HttpHeaderNames.LOCATION)); assertEquals(HttpHeaderNames.LAST_MODIFIED + " does not match", request.headers().getTimeMillis(HttpHeaderNames.LAST_MODIFIED), response.headers().getTimeMillis(HttpHeaderNames.LAST_MODIFIED)); assertEquals(HttpHeaderNames.EXPIRES + " does not match", request.headers().getTimeMillis(HttpHeaderNames.EXPIRES), response.headers().getTimeMillis(HttpHeaderNames.EXPIRES)); assertEquals(HttpHeaderNames.CACHE_CONTROL + " does not match", request.headers().get(HttpHeaderNames.CACHE_CONTROL), response.headers().get(HttpHeaderNames.CACHE_CONTROL)); assertEquals(HttpHeaderNames.PRAGMA + " does not match", request.headers().get(HttpHeaderNames.PRAGMA), response.headers().get(HttpHeaderNames.PRAGMA)); assertEquals(HttpHeaderNames.DATE + " does not match", request.headers().getTimeMillis(HttpHeaderNames.DATE), response.headers().getTimeMillis(HttpHeaderNames.DATE)); assertEquals(MockNettyMessageProcessor.CUSTOM_HEADER_NAME + " does not match", request.headers().get(MockNettyMessageProcessor.CUSTOM_HEADER_NAME), response.headers().get(MockNettyMessageProcessor.CUSTOM_HEADER_NAME)); }
Example #5
Source File: HttpBodySizeRecordingChannelHandler.java From zuul with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { State state = null; // Reset the state as each new inbound request comes in. if (msg instanceof HttpRequest) { state = createNewState(ctx.channel()); } // Update the inbound body size with this chunk. if (msg instanceof HttpContent) { if (state == null) { state = getOrCreateCurrentState(ctx.channel()); } state.inboundBodySize += ((HttpContent) msg).content().readableBytes(); } super.channelRead(ctx, msg); }
Example #6
Source File: HttpsHostCaptureFilter.java From CapturePacket with MIT License | 6 votes |
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; if (ProxyUtils.isCONNECT(httpRequest)) { Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME)); String hostAndPort = httpRequest.getUri(); // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example) // would be unexpected. String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443); hostname.set(hostNoDefaultPort); } } return null; }
Example #7
Source File: WebHdfsHandler.java From hadoop with Apache License 2.0 | 6 votes |
@Override public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception { Preconditions.checkArgument(req.getUri().startsWith(WEBHDFS_PREFIX)); QueryStringDecoder queryString = new QueryStringDecoder(req.getUri()); params = new ParameterParser(queryString, conf); DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params); ugi = ugiProvider.ugi(); path = params.path(); injectToken(); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { handle(ctx, req); return null; } }); }
Example #8
Source File: HttpUtil.java From browserup-proxy with Apache License 2.0 | 6 votes |
/** * Identify the host of an HTTP request. This method uses the URI of the request if possible, otherwise it attempts to find the host * in the request headers. * * @param httpRequest HTTP request to parse the host from * @return the host the request is connecting to, or null if no host can be found */ public static String getHostFromRequest(HttpRequest httpRequest) { // try to use the URI from the request first, if the URI starts with http:// or https://. checking for http/https avoids confusing // java's URI class when the request is for a malformed URL like '//some-resource'. String host = null; if (startsWithHttpOrHttps(httpRequest.getUri())) { try { URI uri = new URI(httpRequest.getUri()); host = uri.getHost(); } catch (URISyntaxException e) { } } // if there was no host in the URI, attempt to grab the host from the Host header if (host == null || host.isEmpty()) { host = parseHostHeader(httpRequest, false); } return host; }
Example #9
Source File: NettyToStyxRequestDecoderTest.java From styx with Apache License 2.0 | 6 votes |
@Test public void acceptsMalformedCookiesWithRelaxedValidation() { HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http://foo.com/"); request.headers().set(HOST, "http://foo.com/"); request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=a,b"); NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder() .uniqueIdSupplier(uniqueIdSupplier) .build(); LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty()) .build(); LiveHttpRequest expected = new LiveHttpRequest.Builder( HttpMethod.GET, "http://foo.com/") .cookies( requestCookie("ABC01", "\"1\""), requestCookie("ABC02", "1"), requestCookie("guid", "a,b") ) .build(); assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies()))); }
Example #10
Source File: HttpLifecycleChannelHandler.java From zuul with Apache License 2.0 | 6 votes |
protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason) { // Only allow this method to run once per request. Attribute<State> attr = ctx.channel().attr(ATTR_STATE); State state = attr.get(); if (state == null || state != State.STARTED) return false; attr.set(State.COMPLETED); HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get(); HttpResponse response = ctx.channel().attr(ATTR_HTTP_RESP).get(); // Cleanup channel attributes. ctx.channel().attr(ATTR_HTTP_REQ).set(null); ctx.channel().attr(ATTR_HTTP_RESP).set(null); // Fire the event to whole pipeline. ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response)); return true; }
Example #11
Source File: ClientRequestCaptureFilter.java From browserup-proxy with Apache License 2.0 | 6 votes |
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { this.httpRequest = (HttpRequest) httpObject; } if (httpObject instanceof HttpContent) { HttpContent httpContent = (HttpContent) httpObject; storeRequestContent(httpContent); if (httpContent instanceof LastHttpContent) { LastHttpContent lastHttpContent = (LastHttpContent) httpContent; trailingHeaders = lastHttpContent .trailingHeaders(); } } return null; }
Example #12
Source File: HttpBodySizeRecordingChannelHandler.java From zuul with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { State state = null; // Reset the state as each new outbound request goes out. if (msg instanceof HttpRequest) { state = createNewState(ctx.channel()); } // Update the outbound body size with this chunk. if (msg instanceof HttpContent) { if (state == null) { state = getOrCreateCurrentState(ctx.channel()); } state.outboundBodySize += ((HttpContent) msg).content().readableBytes(); } super.write(ctx, msg, promise); }
Example #13
Source File: ModelServerTest.java From serve with Apache License 2.0 | 6 votes |
@Test( alwaysRun = true, dependsOnMethods = {"testMetricManager"}) public void testInvalidRootRequest() throws InterruptedException { Channel channel = TestUtils.connect(false, configManager); Assert.assertNotNull(channel); HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); channel.writeAndFlush(req).sync(); channel.closeFuture().sync(); ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class); Assert.assertEquals(resp.getCode(), HttpResponseStatus.METHOD_NOT_ALLOWED.code()); Assert.assertEquals(resp.getMessage(), ERROR_METHOD_NOT_ALLOWED); }
Example #14
Source File: RecordRequestFilter.java From bromium with MIT License | 6 votes |
@Override public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) { for (EventDetector eventDetector: eventDetectors) { if (eventDetector.canDetectPredicate().test(httpRequest)) { try { Optional<Map<String, String>> optionalEvent = eventDetector.getConverter().convert(httpRequest); if (optionalEvent.isPresent()) { Map<String, String> event = optionalEvent.get(); recordingState.storeTestCaseStep(event); logger.info("Recorded event {}", event); } } catch (UnsupportedEncodingException | MalformedURLException e) { logger.error("Error while trying to convert test case step", e); } } } return null; }
Example #15
Source File: Http2FrontendHandler.java From nitmproxy with MIT License | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { LOGGER.info("[Client ({})] => [Server ({})] : {}", connectionInfo.getClientAddr(), connectionInfo.getServerAddr(), msg); if (msg instanceof FullHttpRequest) { String streamId = ((HttpRequest) msg).headers().get( HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { throw new IllegalStateException("No streamId"); } streams.offer(streamId); } else if (msg instanceof HttpObject) { throw new IllegalStateException("Cannot handle message: " + msg.getClass()); } outboundChannel.writeAndFlush(msg); }
Example #16
Source File: WebSocketApplication.java From ext-opensource-netty with Mozilla Public License 2.0 | 6 votes |
@Override public void run(String... strings) { String websocketPath = "/wss"; webScoketServer = new WebSocketServer(); BaseHttpResource httpResource = new HttpResourceThymeleaf(); httpResource.setRootDir("static/websocket/"); httpResource.setDefaultIndexName("websocket.html"); httpResource.setHttpResourceProcess(new HttpResourceProcess() { @Override public void porcessResPath(HttpRequest req, String reqPath, Map<String, Object> reqParameter) { if (httpResource.getDefaultIndexName().equalsIgnoreCase(reqPath) && (reqParameter != null)) { reqParameter.put("socketurl", WebSocketUtil.getWebSocketLocation(webScoketServer.getSslCtx() != null, req, websocketPath)); } } }); webScoketServer.setHttpResource(httpResource); webScoketServer.setWebsocketPath(websocketPath); webScoketServer.setWebSocketEvent(new WebSocketEventChat()); webScoketServer.bind(8989); NettyLog.info("websocket server run end "); }
Example #17
Source File: HttpHelloWorldServerHandler.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
Example #18
Source File: HarCaptureFilter.java From AndroidHttpCapture with MIT License | 6 votes |
protected void captureRequestCookies(HttpRequest httpRequest) { String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE); if (cookieHeader == null) { return; } Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader); for (Cookie cookie : cookies) { HarCookie harCookie = new HarCookie(); harCookie.setName(cookie.name()); harCookie.setValue(cookie.value()); harEntry.getRequest().getCookies().add(harCookie); } }
Example #19
Source File: ProxyRouterEndpointTest.java From riposte with Apache License 2.0 | 5 votes |
public void downstreamRequestFirstChunkInfo_throws_IllegalArgumentException_if_constructed_with_null_host() { // when Throwable ex = catchThrowable( () -> new DownstreamRequestFirstChunkInfo(null, 8080, true, mock(HttpRequest.class)) ); // then assertThat(ex) .isInstanceOf(IllegalArgumentException.class) .hasMessage("host cannot be null."); }
Example #20
Source File: ApplicationMapping.java From minnal with Apache License 2.0 | 5 votes |
/** * Resolves the request to an application by mapping the request url to the application path. * * @param request * @return the application that this request resolves to */ public Application<ApplicationConfiguration> resolve(HttpRequest request) { String path = request.getUri(); for (Entry<String, Application<ApplicationConfiguration>> entry : getSortedApplications().entrySet()) { if (path.startsWith(entry.getKey())) { return entry.getValue(); } } return null; }
Example #21
Source File: RequestToPageLoadingEventConverterTest.java From bromium with MIT License | 5 votes |
@Test public void exceptionIsThrownIfBaseUrlDoesNotMatch() throws MalformedURLException, UnsupportedEncodingException { ActionsFilter actionsFilter = createMocks(false); HttpRequest httpRequest = mock(HttpRequest.class); when(httpRequest.getUri()).thenReturn(WRONG_URL); RequestToPageLoadingEventConverter requestToPageLoadingEventConverter = new RequestToPageLoadingEventConverter(BASE_URL, actionsFilter); expectedException.expect(IllegalArgumentException.class); requestToPageLoadingEventConverter.convert(httpRequest); }
Example #22
Source File: HttpRequestEvent.java From netty-cookbook with Apache License 2.0 | 5 votes |
public HttpRequestEvent(String localIp, String remoteIp, String uriPath, Map<String, List<String>> params, HttpRequest request) { super(); this.localIp = localIp; this.remoteIp = remoteIp; this.uriPath = uriPath; this.params = params; this.request = request; }
Example #23
Source File: ProcessorHttpServer.java From netty-reactive-streams with Apache License 2.0 | 5 votes |
public ChannelFuture bind(SocketAddress address, final Callable<Processor<HttpRequest, HttpResponse>> handler) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(eventLoop) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.AUTO_READ, false) .localAddress(address) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast( new HttpRequestDecoder(), new HttpResponseEncoder() ).addLast("serverStreamsHandler", new HttpStreamsServerHandler()); HandlerSubscriber<HttpResponse> subscriber = new HandlerSubscriber<>(ch.eventLoop(), 2, 4); HandlerPublisher<HttpRequest> publisher = new HandlerPublisher<>(ch.eventLoop(), HttpRequest.class); pipeline.addLast("serverSubscriber", subscriber); pipeline.addLast("serverPublisher", publisher); Processor<HttpRequest, HttpResponse> processor = handler.call(); processor.subscribe(subscriber); publisher.subscribe(processor); } }); return bootstrap.bind(); }
Example #24
Source File: WebSocketIndexPageHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) { String protocol = "ws"; if (cp.get(SslHandler.class) != null) { // SSL in use so use Secure WebSockets protocol = "wss"; } return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path; }
Example #25
Source File: Netty4CorsHandler.java From crate with Apache License 2.0 | 5 votes |
private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) { final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, true, true); if (setOrigin(response)) { setAllowMethods(response); setAllowHeaders(response); setAllowCredentials(response); setMaxAge(response); setPreflightHeaders(response); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { forbidden(ctx, request); } }
Example #26
Source File: Session.java From serve with Apache License 2.0 | 5 votes |
public Session(String remoteIp, HttpRequest request) { this.remoteIp = remoteIp; this.uri = request.uri(); if (request.decoderResult().isSuccess()) { method = request.method().name(); protocol = request.protocolVersion().text(); } else { method = "GET"; protocol = "HTTP/1.1"; } requestId = UUID.randomUUID().toString(); startTime = System.currentTimeMillis(); }
Example #27
Source File: HttpExecutor.java From bitchat with Apache License 2.0 | 5 votes |
private HttpResponse invoke(HttpRequest request) throws Exception { // 根据路由获得具体的ControllerProxy ControllerProxy controllerProxy = controllerContext.getProxy(request.method(), request.uri()); if (controllerProxy == null) { return HttpRenderUtil.getNotFoundResponse(); } // 调用用户自定义的Controller,获得结果 Object result = ProxyInvocation.invoke(controllerProxy); return HttpRenderUtil.render(result, controllerProxy.getRenderType()); }
Example #28
Source File: NettyUtils.java From serve with Apache License 2.0 | 5 votes |
public static void requestReceived(Channel channel, HttpRequest request) { Session session = channel.attr(SESSION_KEY).get(); assert session == null; SocketAddress address = channel.remoteAddress(); String remoteIp; if (address == null) { // This is can be null on UDS, or on certain case in Windows remoteIp = "0.0.0.0"; } else { remoteIp = address.toString(); } channel.attr(SESSION_KEY).set(new Session(remoteIp, request)); }
Example #29
Source File: MethodWebHandlerAdapter.java From CloudNet with Apache License 2.0 | 5 votes |
@Override public FullHttpResponse patch(ChannelHandlerContext channelHandlerContext, QueryDecoder queryDecoder, PathProvider pathProvider, HttpRequest httpRequest) throws Exception { return null; }
Example #30
Source File: ProxyToServerConnection.java From g4proxy with Apache License 2.0 | 5 votes |
@Override protected void requestWriting(HttpRequest httpRequest) { FullFlowContext flowContext = new FullFlowContext(clientConnection, ProxyToServerConnection.this); try { for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.requestSentToServer(flowContext, httpRequest); } } catch (Throwable t) { LOG.warn("Error while invoking ActivityTracker on request", t); } currentFilters.proxyToServerRequestSending(); }