下面列出了 io.netty.handler.codec.http.FullHttpRequest # headers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
HandlerRequest(FullHttpRequest request, Channel channel) {
this.uri = request.uri();
mergeURISlash();
SocketAddress socketAddress = channel.remoteAddress();
if (InetSocketAddress.class.isAssignableFrom(socketAddress.getClass())) {
InetSocketAddress inetSocketAddress = InetSocketAddress.class.cast(socketAddress);
if (inetSocketAddress.getAddress() != null) {
remoteHostAddress = inetSocketAddress.getAddress().getHostAddress();
} else {
remoteHostAddress = inetSocketAddress.getHostString();
}
remotePort = inetSocketAddress.getPort();
}
this.version = request.protocolVersion();
this.method = request.method().name();
this.content = ByteBufUtil.getBytes(request.content());
this.headers = new HttpHeaders(request.headers());
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri(), true);
this.query = new HashMap<>();
queryStringDecoder.parameters().forEach((k, valueList) -> {
if (null != valueList && valueList.size() > EMPTY)
this.query.put(k, valueList.get(0));
});
}
@Override
protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception {
msg.retain();
out.add(msg);
// If the session cookie exists, set its value on the ctx.
final String sessionId = HttpRequestDecoder.getSessionId(msg);
if (sessionId != null) {
ctx.channel().attr(SubscriptionRegistry.SESSION_ID_ATTR).set(sessionId);
LOG.trace("Found sessionId in WebSocket channel, setting sessionId {} on context", sessionId);
}
if (msg.headers() != null) {
ctx.channel().attr(WebSocketRequestDecoder.HTTP_HEADERS_ATTR)
.set(HttpHeaderUtils.toMultimap(msg.headers()));
}
X509Certificate clientCert = AuthenticationService.getClientCertificate(ctx);
if (clientCert != null) {
ctx.channel().attr(WebSocketRequestDecoder.CLIENT_CERT_ATTR).set(clientCert);
}
}
public HttpRequestImpl(FullHttpRequest request) {
this.request = request;
this.parameters = new HashMap<>();
this.headers = request.headers();
this.multipartFiles = new ArrayList<>();
this.uriParser = new URIParser();
// 解析querystring上面的参数
queryStringDecoder = new QueryStringDecoder(request.uri());
uriParser.parse(queryStringDecoder.path());
parameters.putAll(queryStringDecoder.parameters());
in = new InputStreamImpl(request);
if (request.method() == HttpMethod.POST) {
parseHttpPostRequest(request);
}
}
public static OneM2mRequest decode(FullHttpRequest request, String remoteHost) throws Exception {
Byte content[];
String method;
HashMap<String, String> headerMap = new HashMap<String, String>();
HttpHeaders headers = request.headers();
Iterator<Entry<String, String>> it = headers.iterator();
while (it.hasNext()) {
Entry<String, String> header = it.next();
headerMap.put(header.getKey().toUpperCase(), header.getValue());
}
if(request.content().isReadable()) {
return decode(request.getMethod().name(), request.getUri(), headerMap, remoteHost, request.content().copy().array());
} else {
return decode(request.getMethod().name(), request.getUri(), headerMap, remoteHost, null);
}
}
@Test
public void testHeadersOnlyRequest() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET,
"http://[email protected]:5555/example");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpHeaderNames.HOST, "[email protected]:5555");
httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
httpHeaders.add(of("foo"), of("goo"));
httpHeaders.add(of("foo"), of("goo2"));
httpHeaders.add(of("foo2"), of("goo2"));
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/example"))
.authority(new AsciiString("www.example.org:5555")).scheme(new AsciiString("http"))
.add(new AsciiString("foo"), new AsciiString("goo"))
.add(new AsciiString("foo"), new AsciiString("goo2"))
.add(new AsciiString("foo2"), new AsciiString("goo2"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
@Test
public void testMultipleCookieEntriesAreCombined() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET,
"http://[email protected]:5555/example");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpHeaderNames.HOST, "[email protected]:5555");
httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
httpHeaders.set(HttpHeaderNames.COOKIE, "a=b; c=d; e=f");
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/example"))
.authority(new AsciiString("www.example.org:5555")).scheme(new AsciiString("http"))
.add(HttpHeaderNames.COOKIE, "a=b")
.add(HttpHeaderNames.COOKIE, "c=d")
.add(HttpHeaderNames.COOKIE, "e=f");
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
@Test
public void testOriginFormRequestTargetHandledFromUrlencodedUri() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(
HTTP_1_1, GET, "/where%2B0?q=now%2B0&f=then%2B0#section1%2B0");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("GET"))
.path(new AsciiString("/where%2B0?q=now%2B0&f=then%2B0#section1%2B0"))
.scheme(new AsciiString("http"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
@Test
public void testAbsoluteFormRequestTargetHandledFromRequestTargetUri() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET,
"http://[email protected]:5555/pub/WWW/TheProject.html");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("GET"))
.path(new AsciiString("/pub/WWW/TheProject.html"))
.authority(new AsciiString("www.example.org:5555")).scheme(new AsciiString("http"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
/**
* 从httpRequest的Header内摘取出msgId,处于安全考虑,我们只摘取standalone节点传入的msgId <br>
* 如果取不到那么返回null
*/
public static String get(FullHttpRequest fullHttpRequest) {
HttpHeaders httpHeaders = fullHttpRequest.headers();
if (isNodeLegal(httpHeaders) && !StringUtil.isEmpty(httpHeaders.get(Constant.XIAN_MSG_ID_HEADER))) {
return httpHeaders.get(Constant.XIAN_MSG_ID_HEADER);
}
return null;
}
@Override
public CompletableFuture<Response> asyncCall(AsyncHttpRequest req, ServerInstance serverInstance) {
final FullHttpRequest httpRequest = req.getFullHttpRequest();
try {
final AsyncHttpClient httpClient = this.client;
BoundRequestBuilder requestBuilder = new BoundRequestBuilder(httpClient,
httpRequest.method().name(), true);
requestBuilder.setUri(Uri.create(serverInstance.toUri() + req.getRequestPath()));
for (Map.Entry<String, String> headerEntry : httpRequest.headers()) {
if (StringUtils.isNotEmpty(headerEntry.getKey())
&& !"Host".equals(headerEntry.getKey())) {
requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue());
}
}
requestBuilder.addHeader(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
if (httpRequest.content() != null && httpRequest.content().isReadable()) {
//请求body转换为ByteBuffer,并且设置为只读,ByteBuf复用 堆内存中的数据 zero copy
ByteBuffer readOnlyBuffer = httpRequest.content().nioBuffer().asReadOnlyBuffer();
requestBuilder.setBody(readOnlyBuffer);
}
ListenableFuture<Response> listenableFuture = requestBuilder.execute();
return listenableFuture.toCompletableFuture();
} catch (Exception ex) {
log.warn("执行调用报错:{}", ex);
CompletableFuture<Response> exceptionFuture = CompletableFuture.completedFuture(null);
exceptionFuture.completeExceptionally(ex);
return exceptionFuture;
}
}
@Test
public void testAsterikFormRequestTargetHandled() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, OPTIONS, "*");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpHeaderNames.HOST, "www.example.com:80");
httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("OPTIONS")).path(new AsciiString("*"))
.scheme(new AsciiString("http")).authority(new AsciiString("www.example.com:80"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
@Test
public void testAuthorityFormRequestTargetHandled() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, CONNECT, "http://www.example.com:80");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("CONNECT")).path(new AsciiString("/"))
.scheme(new AsciiString("http")).authority(new AsciiString("www.example.com:80"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
/**
* Creates the container request from the http request
*
* @param httpRequest
* @return
*/
protected ContainerRequest createContainerRequest(MessageContext context) {
Application<ApplicationConfiguration> application = context.getApplication();
FullHttpRequest httpRequest = context.getRequest();
URI baseUri = URI.create(context.getBaseUri().resolve(application.getPath()) + "/");
URI requestUri = HttpUtil.createURI(httpRequest.getUri());
ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri, httpRequest.getMethod().name(), null, new MapPropertiesDelegate());
// containerRequest.setProperty(REQUEST_PROPERTY_REMOTE_ADDR, context.getRequest().channel().remoteAddress());
containerRequest.setEntityStream(new ByteBufInputStream(httpRequest.content()));
for (Map.Entry<String, String> headerEntry : httpRequest.headers()) {
containerRequest.getHeaders().add(headerEntry.getKey(), headerEntry.getValue());
}
return containerRequest;
}
@Test
public void clientRequestMultipleEmptyDataFrames() throws Exception {
boostrapEnv(1, 1, 1);
final String text = "";
final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/some/path/resource2", content, true);
try {
HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
new AsciiString("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
clientChannel.flush();
}
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
verify(serverListener).messageReceived(requestCaptor.capture());
capturedRequests = requestCaptor.getAllValues();
assertEquals(request, capturedRequests.get(0));
} finally {
request.release();
}
}
@Test
public void testOriginFormRequestTargetHandled() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/where?q=now&f=then#section1");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("GET"))
.path(new AsciiString("/where?q=now&f=then#section1"))
.scheme(new AsciiString("http"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
@Test
public void testHostIPv4FormRequestTargetHandled() throws Exception {
bootstrapEnv(2, 1, 0);
final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/");
final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpHeaderNames.HOST, "1.2.3.4:80");
httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
final Http2Headers http2Headers =
new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/"))
.scheme(new AsciiString("http")).authority(new AsciiString("1.2.3.4:80"));
ChannelPromise writePromise = newPromise();
verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
/**
* /**
* <p>
* Sends the opening request to the server:
* </p>
*
* <pre>
* GET /chat HTTP/1.1
* Host: server.example.com
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
* Sec-WebSocket-Origin: http://example.com
* Sec-WebSocket-Protocol: chat, superchat
* Sec-WebSocket-Version: 13
* </pre>
*
*/
@Override
protected FullHttpRequest newHandshakeRequest() {
// Get path
URI wsURL = uri();
String path = rawPath(wsURL);
// Get 16 bit nonce and base 64 encode it
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug(
"WebSocket version 13 client handshake key: {}, expected response: {}",
key, expectedChallengeResponseString);
}
// Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers();
headers.add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.add(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.add(HttpHeaderNames.HOST, websocketHostValue(wsURL))
.add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.add(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
if (customHeaders != null) {
headers.add(customHeaders);
}
return request;
}
public FullHttp1Request(FullHttpRequest delegate, TraceInfo traceInfo) {
this.delegate = delegate;
this.headers = new Http1Headers(delegate.headers());
this.traceInfo = traceInfo == null ? new TraceInfo(headers) : traceInfo;
}
/**
* /**
* <p>
* Sends the opening request to the server:
* </p>
*
* <pre>
* GET /chat HTTP/1.1
* Host: server.example.com
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
* Sec-WebSocket-Origin: http://example.com
* Sec-WebSocket-Protocol: chat, superchat
* Sec-WebSocket-Version: 13
* </pre>
*
*/
@Override
protected FullHttpRequest newHandshakeRequest() {
// Get path
URI wsURL = uri();
String path = wsURL.getPath();
if (wsURL.getQuery() != null && !wsURL.getQuery().isEmpty()) {
path = wsURL.getPath() + '?' + wsURL.getQuery();
}
if (path == null || path.isEmpty()) {
path = "/";
}
// Get 16 bit nonce and base 64 encode it
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug(
"WebSocket version 13 client handshake key: {}, expected response: {}",
key, expectedChallengeResponseString);
}
// Format request
int wsPort = wsURL.getPort();
// check if the URI contained a port if not set the correct one depending on the schema.
// See https://github.com/netty/netty/pull/1558
if (wsPort == -1) {
if ("wss".equals(wsURL.getScheme())) {
wsPort = 443;
} else {
wsPort = 80;
}
}
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers();
headers.add(Names.UPGRADE, Values.WEBSOCKET.toLowerCase())
.add(Names.CONNECTION, Values.UPGRADE)
.add(Names.SEC_WEBSOCKET_KEY, key)
.add(Names.HOST, wsURL.getHost() + ':' + wsPort);
String originValue = "http://" + wsURL.getHost();
if (wsPort != 80 && wsPort != 443) {
// if the port is not standard (80/443) its needed to add the port to the header.
// See http://tools.ietf.org/html/rfc6454#section-6.2
originValue = originValue + ':' + wsPort;
}
headers.add(Names.SEC_WEBSOCKET_ORIGIN, originValue);
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.add(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.add(Names.SEC_WEBSOCKET_VERSION, "13");
if (customHeaders != null) {
headers.add(customHeaders);
}
return request;
}
@Test
public void clientRequestTrailingHeaders() throws Exception {
boostrapEnv(1, 1, 1);
final String text = "some data";
final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/some/path/resource2", content, true);
try {
HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
HttpHeaders trailingHeaders = request.trailingHeaders();
trailingHeaders.set(of("Foo"), of("goo"));
trailingHeaders.set(of("fOo2"), of("goo2"));
trailingHeaders.add(of("foO2"), of("goo3"));
final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
new AsciiString("/some/path/resource2"));
final Http2Headers http2Headers2 = new DefaultHttp2Headers()
.set(new AsciiString("foo"), new AsciiString("goo"))
.set(new AsciiString("foo2"), new AsciiString("goo2"))
.add(new AsciiString("foo2"), new AsciiString("goo3"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, false,
newPromiseClient());
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers2, 0, true, newPromiseClient());
clientChannel.flush();
}
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
verify(serverListener).messageReceived(requestCaptor.capture());
capturedRequests = requestCaptor.getAllValues();
assertEquals(request, capturedRequests.get(0));
} finally {
request.release();
}
}