io.netty.handler.codec.http.HttpRequest类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(13.4k)|赞(0)|评价(0)|浏览(228)

本文整理了Java中io.netty.handler.codec.http.HttpRequest类的一些代码示例,展示了HttpRequest类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpRequest类的具体详情如下:
包路径:io.netty.handler.codec.http.HttpRequest
类名称:HttpRequest

HttpRequest介绍

[英]An HTTP request.

Unlike the Servlet API, a query string is constructed and decomposed by QueryStringEncoder and QueryStringDecoder. io.netty.handler.codec.http.cookie.Cookie support is also provided separately via io.netty.handler.codec.http.cookie.ServerCookieDecoder, io.netty.handler.codec.http.cookie.ClientCookieDecoder, io.netty.handler.codec.http.cookie.ServerCookieEncoder, and io.netty.handler.codec.http.cookie.ClientCookieEncoder.
[中]HTTP请求。
####访问查询参数和Cookie
与ServletAPI不同,查询字符串由QueryStringEncoder和QueryStringDecoder构造和分解。木卫一。内蒂。处理程序。编解码器。http。曲奇Cookie支持也通过io单独提供。内蒂。处理程序。编解码器。http。曲奇服务器CookieDecoder,io。内蒂。处理程序。编解码器。http。曲奇客户端CookieDecoder,io。内蒂。处理程序。编解码器。http。曲奇ServerCookieEncoder和io。内蒂。处理程序。编解码器。http。曲奇ClientCookie编码器。

代码示例

代码示例来源:origin: eclipse-vertx/vert.x

static String getWebSocketLocation(HttpRequest req, boolean ssl) throws Exception {
 String prefix;
 if (ssl) {
  prefix = "ws://";
 } else {
  prefix = "wss://";
 }
 URI uri = new URI(req.uri());
 String path = uri.getRawPath();
 String loc = prefix + req.headers().get(HttpHeaderNames.HOST) + path;
 String query = uri.getRawQuery();
 if (query != null) {
  loc += "?" + query;
 }
 return loc;
}

代码示例来源:origin: micronaut-projects/micronaut-core

/**
 * @param nettyRequest      The Http netty request
 * @param conversionService The conversion service
 */
public AbstractNettyHttpRequest(io.netty.handler.codec.http.HttpRequest nettyRequest, ConversionService conversionService) {
  this.nettyRequest = nettyRequest;
  this.conversionService = conversionService;
  String fullUri = nettyRequest.uri();
  this.uri = URI.create(fullUri);
  this.httpMethod = HttpMethod.valueOf(nettyRequest.method().name());
}

代码示例来源:origin: JZ-Darkal/AndroidHttpCapture

protected void captureRequestHeaderSize(HttpRequest httpRequest) {
  String requestLine = httpRequest.getMethod().toString() + ' ' + httpRequest.getUri() + ' ' + httpRequest.getProtocolVersion().toString();
  // +2 => CRLF after status line, +4 => header/data separation
  long requestHeadersSize = requestLine.length() + 6;
  HttpHeaders headers = httpRequest.headers();
  requestHeadersSize += BrowserMobHttpUtil.getHeaderSize(headers);
  harEntry.getRequest().setHeadersSize(requestHeadersSize);
}

代码示例来源:origin: mrniko/netty-socketio

private String getWebSocketLocation(HttpRequest req) {
  String protocol = "ws://";
  if (isSsl) {
    protocol = "wss://";
  }
  return protocol + req.headers().get(HttpHeaderNames.HOST) + req.uri();
}

代码示例来源:origin: wildfly/wildfly

private static boolean isPreflightRequest(final HttpRequest request) {
  final HttpHeaders headers = request.headers();
  return request.method().equals(OPTIONS) &&
      headers.contains(HttpHeaderNames.ORIGIN) &&
      headers.contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD);
}

代码示例来源:origin: GlowstoneMC/Glowstone

URI uri = URI.create(url);
String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
  .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
  .connect(InetSocketAddress.createUnresolved(host, port))
  .addListener((ChannelFutureListener) future -> {
    if (future.isSuccess()) {
      String path = uri.getRawPath() + (uri.getRawQuery() == null ? ""
        : "?" + uri.getRawQuery());
      HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
        HttpMethod.GET, path);
      request.headers().set(HttpHeaderNames.HOST, host);
      future.channel().writeAndFlush(request);
    } else {
      callback.error(future.cause());

代码示例来源:origin: linkedin/flashback

public void interpretHttpRequest(HttpRequest nettyHttpRequest) {
 _httpMethod = nettyHttpRequest.getMethod().toString();
 try {
  URI uri = new URI(nettyHttpRequest.getUri());
  if (uri.isAbsolute()) {
   _uri = uri;
  } else {
   String hostName = nettyHttpRequest.headers().get(HttpHeaders.Names.HOST);
   if (!Strings.isNullOrEmpty(hostName)) {
    _uri = new URI(String.format("https://%s%s", hostName, uri));
   } else {
    _path = uri.toString();
   }
  }
 } catch (URISyntaxException e) {
  throw new IllegalStateException("Invalid URI in underlying request", e);
 }
}

代码示例来源:origin: jersey/jersey

String host = requestUri.getHost();
int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
  final Channel ch = b.connect(host, port).sync().channel();
  ch.closeFuture().addListener(closeListener);
                       HttpMethod.valueOf(jerseyRequest.getMethod()),
                       requestUri.getRawPath());
  } else {
    nettyRequest.headers().add(e.getKey(), e.getValue());
  nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
      HttpUtil.setTransferEncodingChunked(nettyRequest, true);
    } else {
      nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());

代码示例来源:origin: wildfly/wildfly

future.awaitUninterruptibly();
     URI uri = new URI(scheme, null, ipv6Host, port, null, null, null);
     HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
     request.headers().set(HttpHeaderNames.HOST, ipv6Host);
     request.headers().set(HttpHeaderNames.UPGRADE, ACTIVEMQ_REMOTING);
     request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.UPGRADE);
     final String serverName = ConfigurationHelper.getStringProperty(TransportConstants.ACTIVEMQ_SERVER_NAME, null, configuration);
     if (serverName != null) {
      request.headers().set(TransportConstants.ACTIVEMQ_SERVER_NAME, serverName);
      request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
     request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
     ch.attr(REMOTING_KEY).set(key);

代码示例来源:origin: linkedin/flashback

@Test
public void testBuildRelativeUri() {
 String uri = "finance";
 HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri);
 nettyRequest.headers().set(HttpHeaders.Names.HOST, "www.google.com/");
 RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);
 RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
 Assert.assertEquals(recordedHttpRequest.getUri().toString(), "https://www.google.com/finance");
}

代码示例来源:origin: jersey/jersey

String s = req.uri().startsWith("/") ? req.uri().substring(1) : req.uri();
URI requestUri = URI.create(baseUri + ContainerUtils.encodeUnsafeCharacters(s));
    baseUri, requestUri, req.method().name(), getSecurityContext(),
    new PropertiesDelegate() {
if ((req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(req) > 0)
    || HttpUtil.isTransferEncodingChunked(req)) {
  ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
    @Override
    public void operationComplete(Future<? super Void> future) throws Exception {
for (String name : req.headers().names()) {
  requestContext.headers(name, req.headers().getAll(name));

代码示例来源:origin: SpigotMC/BungeeCord

@Override
  public void operationComplete(ChannelFuture future) throws Exception
  {
    if ( future.isSuccess() )
    {
      String path = uri.getRawPath() + ( ( uri.getRawQuery() == null ) ? "" : "?" + uri.getRawQuery() );
      HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, path );
      request.headers().set( HttpHeaders.Names.HOST, uri.getHost() );
      future.channel().writeAndFlush( request );
    } else
    {
      addressCache.invalidate( uri.getHost() );
      callback.done( null, future.cause() );
    }
  }
};

代码示例来源:origin: wildfly/wildfly

final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
if (in instanceof HttpRequest) {
  HttpRequest request = (HttpRequest) in;
  URI requestTargetUri = URI.create(request.uri());
  out.path(toHttp2Path(requestTargetUri));
  out.method(request.method().asciiName());
  setHttp2Scheme(inHeaders, requestTargetUri, out);
    String host = inHeaders.getAsString(HttpHeaderNames.HOST);
    setHttp2Authority((host == null || host.isEmpty()) ? requestTargetUri.getAuthority() : host, out);

代码示例来源:origin: org.apache.hadoop/hadoop-hdfs

@Override
 public void operationComplete(ChannelFuture future) throws Exception {
  if (future.isSuccess()) {
   ctx.channel().pipeline().remove(HttpResponseEncoder.class);
   HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
    req.getMethod(), req.getUri());
   newReq.headers().add(req.headers());
   newReq.headers().set(CONNECTION, Values.CLOSE);
   future.channel().writeAndFlush(newReq);
  } else {
   DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
    INTERNAL_SERVER_ERROR);
   resp.headers().set(CONNECTION, Values.CLOSE);
   LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
   ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
   client.close();
  }
 }
});

代码示例来源:origin: resteasy/Resteasy

public static ResteasyUriInfo extractUriInfo(HttpRequest request, String contextPath, String protocol)
{
 String host = request.headers().get(HttpHeaderNames.HOST, "unknown");
 String uri = request.uri();
 String uriString;
 // If we appear to have an absolute URL, don't try to recreate it from the host and request line.
 if (uri.startsWith(protocol + "://")) {
   uriString = uri;
 } else {
   uriString = protocol + "://" + host + uri;
 }
 URI absoluteURI = URI.create(uriString);
 return new ResteasyUriInfo(uriString, absoluteURI.getRawQuery(), contextPath);
}

代码示例来源:origin: micronaut-projects/micronaut-core

);
        try {
          nettyRequest.setUri(requestURI.toURL().getFile());
        } catch (MalformedURLException e) {
  nettyRequest.setUri(requestURI.toURL().getFile());
} catch (MalformedURLException e) {

代码示例来源:origin: eclipse-vertx/vert.x

if (msg instanceof HttpRequest) {
 HttpRequest request = (HttpRequest) msg;
 if (request.headers().contains(io.vertx.core.http.HttpHeaders.UPGRADE, Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, true)) {
  String connection = request.headers().get(io.vertx.core.http.HttpHeaders.CONNECTION);
  int found = 0;
  if (connection != null && connection.length() > 0) {
   String settingsHeader = request.headers().get(Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER);
   if (settingsHeader != null) {
    Http2Settings settings = HttpUtils.decodeSettings(settingsHeader);
    if (settings != null) {
     HandlerHolder<HttpHandlers> reqHandler = httpHandlerMgr.chooseHandler(ctx.channel().eventLoop());
     if (reqHandler != null && reqHandler.context.isEventLoopContext()) {
      ChannelPipeline pipeline = ctx.pipeline();
      ctx.writeAndFlush(res);
      pipeline.remove("httpEncoder");
      pipeline.remove("handler");
      handler.serverUpgrade(ctx, settings, request);
      DefaultHttp2Headers headers = new DefaultHttp2Headers();
      headers.method(request.method().name());
      headers.path(request.uri());
      headers.authority(request.headers().get("host"));
      headers.scheme("http");
      request.headers().remove("http2-settings");
      request.headers().remove("host");
      request.headers().forEach(header -> headers.set(header.getKey().toLowerCase(), header.getValue()));

代码示例来源:origin: Netflix/zuul

@Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
  {
    if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent)
    {
      // Get the stored request, and remove the attr from channel to cleanup.
      RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get();
      ctx.channel().attr(ATTR_REQ_STATE).set(null);
      // Response complete, so now write to access log.
      long durationNs = System.nanoTime() - state.startTimeNs;
      String remoteIp = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get();
      Integer localPort = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get();
      if (state.response == null) {
        LOG.debug("Response null in AccessLog, Complete reason={}, duration={}, url={}, method={}",
            ((HttpLifecycleChannelHandler.CompleteEvent)evt).getReason(),
            durationNs/(1000*1000), state.request != null ? state.request.uri() : "-",
            state.request != null ? state.request.method() : "-");
      }
      publisher.log(ctx.channel(), state.request, state.response, state.dateTime, localPort, remoteIp, durationNs,
          state.requestBodySize, state.responseBodySize);
    }
    super.userEventTriggered(ctx, evt);
  }
}

代码示例来源:origin: jersey/jersey

response = new DefaultFullHttpResponse(req.protocolVersion(), status);
} else {
  response = new DefaultHttpResponse(req.protocolVersion(), status);
  response.headers().add(e.getKey(), e.getValue());
  HttpUtil.setTransferEncodingChunked(response, true);
} else {
  response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
  response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.writeAndFlush(response);
if (req.method() != HttpMethod.HEAD && (contentLength > 0 || contentLength == -1)) {
  JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());
    ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
  } else {
    ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);

代码示例来源:origin: apache/incubator-dubbo

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
  CommandContext commandContext = HttpCommandDecoder.decode(msg);
  // return 404 when fail to construct command context
  if (commandContext == null) {
    log.warn("can not found commandContext url: " + msg.getUri());
    FullHttpResponse response = http404();
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  } else {
    commandContext.setRemote(ctx.channel());
    try {
      String result = commandExecutor.execute(commandContext);
      FullHttpResponse response = http200(result);
      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } catch (NoSuchCommandException ex) {
      log.error("can not find commandContext: " + commandContext, ex);
      FullHttpResponse response = http404();
      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } catch (Exception qosEx) {
      log.error("execute commandContext: " + commandContext + " got exception", qosEx);
      FullHttpResponse response = http500(qosEx.getMessage());
      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
  }
}

相关文章