下面列出了 io.netty.handler.codec.http.HttpRequest # headers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static HttpRequest adapter(HttpRequest httpRequest) {
if (httpRequest instanceof DefaultHttpRequest) {
HttpVer version;
if (httpRequest.protocolVersion().minorVersion() == 0) {
version = HttpVer.HTTP_1_0;
} else {
version = HttpVer.HTTP_1_1;
}
HttpHeadsInfo httpHeadsInfo = new HttpHeadsInfo();
for (Entry<String, String> entry : httpRequest.headers()) {
httpHeadsInfo.set(entry.getKey(), entry.getValue());
}
return new HttpRequestInfo(version, httpRequest.method(), httpRequest.uri(),
httpHeadsInfo, null);
}
return httpRequest;
}
public RequestInfoImpl(@NotNull HttpRequest request) {
this(
request.uri(),
request.method(),
request.headers(),
HttpUtils.extractTrailingHeadersIfPossible(request),
null,
HttpUtils.extractCookies(request),
null,
HttpUtils.extractContentChunks(request),
request.protocolVersion(),
HttpUtil.isKeepAlive(request),
(request instanceof FullHttpRequest),
HttpPostRequestDecoder.isMultipart(request)
);
}
protected void captureRequestHeaderSize(HttpRequest httpRequest) {
String requestLine = httpRequest.method().toString() + ' ' + httpRequest.uri() + ' ' + httpRequest.protocolVersion().toString();
// +2 => CRLF after status line, +4 => header/data separation
long requestHeadersSize = requestLine.length() + 6;
HttpHeaders headers = httpRequest.headers();
requestHeadersSize += BrowserUpHttpUtil.getHeaderSize(headers);
harEntry.getRequest().setHeadersSize(requestHeadersSize);
}
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
if (isDebug) {
logger.afterInterceptor(target, args, result, throwable);
}
final Trace trace = traceContext.currentTraceObject();
if (trace == null) {
return;
}
try {
final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordApi(descriptor);
recorder.recordException(throwable);
recorder.recordServiceType(VertxConstants.VERTX_HTTP_CLIENT);
if (!validate(args)) {
return;
}
final HttpRequest request = (HttpRequest) args[0];
final HttpHeaders headers = request.headers();
if (headers == null) {
return;
}
final String host = (String) args[1];
ClientRequestWrapper clientRequest = new VertxHttpClientRequestWrapper(request, host);
this.clientRequestRecorder.record(recorder, clientRequest, throwable);
this.cookieRecorder.record(recorder, request, throwable);
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("AFTER. Caused:{}", t.getMessage(), t);
}
} finally {
trace.traceBlockEnd();
}
}
@Override
public void before(Object target, Object[] args) {
if (isDebug) {
logger.beforeInterceptor(target, args);
}
final Trace trace = traceContext.currentTraceObject();
if (trace == null) {
return;
}
try {
final SpanEventRecorder recorder = trace.traceBlockBegin();
if (!validate(args)) {
return;
}
final HttpRequest request = (HttpRequest) args[0];
final HttpHeaders headers = request.headers();
if (headers == null) {
// defense code.
return;
}
final String host = (String) args[1];
// generate next trace id.
final TraceId nextId = trace.getTraceId().getNextTraceId();
recorder.recordNextSpanId(nextId.getSpanId());
requestTraceWriter.write(request, nextId, host);
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("BEFORE. Caused:{}", t.getMessage(), t);
}
}
}
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);
}
/**
* If and only if our proxy is not running in transparent mode, modify the
* request headers to reflect that it was proxied.
*
* @param httpRequest
*/
private void modifyRequestHeadersToReflectProxying(HttpRequest httpRequest) {
if (!currentServerConnection.hasUpstreamChainedProxy()) {
/*
* We are making the request to the origin server, so must modify
* the 'absolute-URI' into the 'origin-form' as per RFC 7230
* section 5.3.1.
*
* This must happen even for 'transparent' mode, otherwise the origin
* server could infer that the request came via a proxy server.
*/
LOG.debug("Modifying request for proxy chaining");
// Strip host from uri
String uri = httpRequest.getUri();
String adjustedUri = ProxyUtils.stripHost(uri);
LOG.debug("Stripped host from uri: {} yielding: {}", uri,
adjustedUri);
httpRequest.setUri(adjustedUri);
}
if (!proxyServer.isTransparent()) {
LOG.debug("Modifying request headers for proxying");
HttpHeaders headers = httpRequest.headers();
// Remove sdch from encodings we accept since we can't decode it.
ProxyUtils.removeSdchEncoding(headers);
switchProxyConnectionHeader(headers);
stripConnectionTokens(headers);
stripHopByHopHeaders(headers);
ProxyUtils.addVia(httpRequest, proxyServer.getProxyAlias());
}
}
/**
* Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers.
* The following headers are only used if they can not be found in the {@code HOST} header or the
* {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
* <ul>
* <li>{@link ExtensionHeaderNames#SCHEME}</li>
* </ul>
* {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
*/
public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in,
ServerConfig cfg) throws URISyntaxException {
final URI requestTargetUri = toUri(in);
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final RequestHeadersBuilder out = RequestHeaders.builder();
out.sizeHint(inHeaders.size());
out.add(HttpHeaderNames.METHOD, in.method().name());
out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri));
addHttp2Scheme(inHeaders, requestTargetUri, out);
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
if (!out.contains(HttpHeaderNames.HOST)) {
// The client violates the spec that the request headers must contain a Host header.
// But we just add Host header to allow the request.
// https://tools.ietf.org/html/rfc7230#section-5.4
if (isOriginForm(requestTargetUri) || isAsteriskForm(requestTargetUri)) {
// requestTargetUri does not contain authority information.
final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
out.add(HttpHeaderNames.HOST, defaultHostname + ':' + port);
} else {
out.add(HttpHeaderNames.HOST, stripUserInfo(requestTargetUri.getAuthority()));
}
}
return out.build();
}
public NettyHttpServletRequest(ChannelHandlerContext ctx, ServletContentHandler handler, HttpRequest request, HttpServletResponse servletResponse) {
this.ctx = ctx;
this.servletContext = handler.getServletContext();
this.request = request;
this.servletResponse = servletResponse;
this.inputStream = handler.getInputStream();
this.attributes = new ConcurrentHashMap<>();
this.headers = request.headers();
parseSession();
}
private HttpHeadersFrame createHttpHeadersFrame(HttpRequest httpRequest)
throws Exception {
// Get the Stream-ID from the headers
int streamId = HttpHeaders.getIntHeader(httpRequest, "X-SPDY-Stream-ID");
httpRequest.headers().remove("X-SPDY-Stream-ID");
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent.
httpRequest.headers().remove(HttpHeaders.Names.CONNECTION);
httpRequest.headers().remove("Keep-Alive");
httpRequest.headers().remove("Proxy-Connection");
httpRequest.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);
HttpHeadersFrame httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
// Unfold the first line of the request into name/value pairs
httpHeadersFrame.headers().add(":method", httpRequest.getMethod().name());
httpHeadersFrame.headers().set(":scheme", "https");
httpHeadersFrame.headers().add(":path", httpRequest.getUri());
// Replace the HTTP host header with the SPDY host header
String host = httpRequest.headers().get(HttpHeaders.Names.HOST);
httpRequest.headers().remove(HttpHeaders.Names.HOST);
httpHeadersFrame.headers().add(":authority", host);
// Transfer the remaining HTTP headers
for (Map.Entry<String, String> entry : httpRequest.headers()) {
httpHeadersFrame.headers().add(entry.getKey(), entry.getValue());
}
return httpHeadersFrame;
}
protected void captureRequestHeaderSize(HttpRequest httpRequest) {
Log.e("InnerHandle", "captureRequestHeaderSize " + harEntry.getId());
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);
harRequest.getRequest().setHeadersSize(requestHeadersSize);
}
protected void captureRequestHeaders(HttpRequest httpRequest) {
HttpHeaders headers = httpRequest.headers();
captureHeaders(headers);
}
public static void newHttpClientBootstrap(String url, ChannelHandler handler) 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;
} 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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new HttpDownloadertInitializer(sslCtx,handler));
// 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());
HttpHeaders headers = request.headers();
headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaderNames.CONNECTION,HttpHeaderValues.CLOSE);
headers.set(HttpHeaderNames.ACCEPT_ENCODING,HttpHeaderValues.GZIP);
// Set some example cookies.
headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
Thread.sleep(1000);
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}
public static void newHttpClientBootstrap(String url, ChannelHandler handler) 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;
} 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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new HttpDownloadertInitializer(sslCtx,handler));
// 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());
HttpHeaders headers = request.headers();
headers.set(HttpHeaders.Names.HOST, host);
headers.set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
headers.set(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
// Set some example cookies.
headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
Thread.sleep(1000);
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}
protected void captureRequestHeaders(HttpRequest httpRequest) {
Log.e("InnerHandle", "captureRequestHeaders " + harEntry.getId());
HttpHeaders headers = httpRequest.headers();
captureHeaders(headers);
}
protected void captureRequestHeaders(HttpRequest httpRequest) {
HttpHeaders headers = httpRequest.headers();
captureHeaders(headers);
}
public static void newHttpClientBootstrap(String url, ChannelHandler handler) 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;
} 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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new HttpDownloadertInitializer(sslCtx,handler));
// 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());
HttpHeaders headers = request.headers();
headers.set(HttpHeaders.Names.HOST, host);
headers.set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
headers.set(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
// Set some example cookies.
headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
Thread.sleep(1000);
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}
private static boolean isPreflightRequest(final HttpRequest request) {
final HttpHeaders headers = request.headers();
return request.method().equals(HttpMethod.OPTIONS) &&
headers.contains(HttpHeaderNames.ORIGIN) &&
headers.contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD);
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
*
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String, String>> formget(
Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
Channel channel = bootstrap.connect(host, port).sync().channel();
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform", "GET");
encoder.addParam("info", "first value");
encoder.addParam("secondinfo", "secondvalue ���&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send", "Send");
URI uriGet = new URI(encoder.toString());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
HttpHeaders headers = request.headers();
headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//connection will not close but needed
// headers.set("Connection","keep-alive");
// headers.set("Keep-Alive","300");
headers.set(
HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))
);
// send request
channel.writeAndFlush(request);
// Wait for the server to close the connection.
channel.closeFuture().sync();
// convert headers to list
return headers.entries();
}
public static void newHttpClientBootstrap(String url, ChannelHandler handler) 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;
} 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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new HttpDownloadertInitializer(sslCtx,handler));
// 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());
HttpHeaders headers = request.headers();
headers.set(HttpHeaders.Names.HOST, host);
headers.set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
headers.set(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
// Set some example cookies.
headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
ch.writeAndFlush(request);
// Wait for the server to close the connection.
ch.closeFuture().sync();
Thread.sleep(1000);
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
}
}