下面列出了怎么用 io.netty.handler.codec.http.HttpScheme 的API类实例代码及写法,或者点击链接到github查看源代码。
static CharSequence websocketHostValue(URI wsURL) {
int port = wsURL.getPort();
if (port == -1) {
return wsURL.getHost();
}
String host = wsURL.getHost();
if (port == HttpScheme.HTTP.port()) {
return HttpScheme.HTTP.name().contentEquals(wsURL.getScheme())
|| WebSocketScheme.WS.name().contentEquals(wsURL.getScheme()) ?
host : NetUtil.toSocketAddressString(host, port);
}
if (port == HttpScheme.HTTPS.port()) {
return HttpScheme.HTTPS.name().contentEquals(wsURL.getScheme())
|| WebSocketScheme.WSS.name().contentEquals(wsURL.getScheme()) ?
host : NetUtil.toSocketAddressString(host, port);
}
// 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
return NetUtil.toSocketAddressString(host, port);
}
static CharSequence websocketOriginValue(URI wsURL) {
String scheme = wsURL.getScheme();
final String schemePrefix;
int port = wsURL.getPort();
final int defaultPort;
if (WebSocketScheme.WSS.name().contentEquals(scheme)
|| HttpScheme.HTTPS.name().contentEquals(scheme)
|| (scheme == null && port == WebSocketScheme.WSS.port())) {
schemePrefix = HTTPS_SCHEME_PREFIX;
defaultPort = WebSocketScheme.WSS.port();
} else {
schemePrefix = HTTP_SCHEME_PREFIX;
defaultPort = WebSocketScheme.WS.port();
}
// Convert uri-host to lower case (by RFC 6454, chapter 4 "Origin of a URI")
String host = wsURL.getHost().toLowerCase(Locale.US);
if (port != defaultPort && port != -1) {
// 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
return schemePrefix + NetUtil.toSocketAddressString(host, port);
}
return schemePrefix + host;
}
@Test
public void decode100ContinueHttp2HeadersAsFullHttpResponse() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
Http2Headers headers = new DefaultHttp2Headers();
headers.scheme(HttpScheme.HTTP.name());
headers.status(HttpResponseStatus.CONTINUE.codeAsText());
assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers, false)));
final FullHttpResponse response = ch.readInbound();
try {
assertThat(response.status(), is(HttpResponseStatus.CONTINUE));
assertThat(response.protocolVersion(), is(HttpVersion.HTTP_1_1));
} finally {
response.release();
}
assertThat(ch.readInbound(), is(nullValue()));
assertFalse(ch.finish());
}
@Test
public void testDecodeResponseHeaders() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
Http2Headers headers = new DefaultHttp2Headers();
headers.scheme(HttpScheme.HTTP.name());
headers.status(HttpResponseStatus.OK.codeAsText());
assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers)));
HttpResponse response = ch.readInbound();
assertThat(response.status(), is(HttpResponseStatus.OK));
assertThat(response.protocolVersion(), is(HttpVersion.HTTP_1_1));
assertFalse(response instanceof FullHttpResponse);
assertTrue(HttpUtil.isTransferEncodingChunked(response));
assertThat(ch.readInbound(), is(nullValue()));
assertFalse(ch.finish());
}
@Test
public void testDecodeResponseHeadersWithContentLength() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
Http2Headers headers = new DefaultHttp2Headers();
headers.scheme(HttpScheme.HTTP.name());
headers.status(HttpResponseStatus.OK.codeAsText());
headers.setInt("content-length", 0);
assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers)));
HttpResponse response = ch.readInbound();
assertThat(response.status(), is(HttpResponseStatus.OK));
assertThat(response.protocolVersion(), is(HttpVersion.HTTP_1_1));
assertFalse(response instanceof FullHttpResponse);
assertFalse(HttpUtil.isTransferEncodingChunked(response));
assertThat(ch.readInbound(), is(nullValue()));
assertFalse(ch.finish());
}
@Test
public void testDecodeFullResponseHeaders() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
Http2Headers headers = new DefaultHttp2Headers();
headers.scheme(HttpScheme.HTTP.name());
headers.status(HttpResponseStatus.OK.codeAsText());
assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers, true)));
FullHttpResponse response = ch.readInbound();
try {
assertThat(response.status(), is(HttpResponseStatus.OK));
assertThat(response.protocolVersion(), is(HttpVersion.HTTP_1_1));
assertThat(response.content().readableBytes(), is(0));
assertTrue(response.trailingHeaders().isEmpty());
assertFalse(HttpUtil.isTransferEncodingChunked(response));
} finally {
response.release();
}
assertThat(ch.readInbound(), is(nullValue()));
assertFalse(ch.finish());
}
protected FullHttpRequest convertToHttpRequest(SofaRequest request) {
HttpScheme scheme = SslContextBuilder.SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
AsciiString hostName = new AsciiString(providerInfo.getHost() + ':' + providerInfo.getPort());
String url = "/" + request.getTargetServiceUniqueName() + "/" + request.getMethodName();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("send request to url :{}", url);
}
// Create a simple POST request with a body.
FullHttpRequest httpRequest = new DefaultFullHttpRequest(HTTP_1_1, POST, url,
wrappedBuffer(request.getData().array()));
HttpHeaders headers = httpRequest.headers();
addToHeader(headers, HttpHeaderNames.HOST, hostName);
addToHeader(headers, HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
addToHeader(headers, HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
addToHeader(headers, HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
addToHeader(headers, RemotingConstants.HEAD_SERIALIZE_TYPE,
SerializerFactory.getAliasByCode(request.getSerializeType()));
addToHeader(headers, RemotingConstants.HEAD_TARGET_APP, request.getTargetAppName());
Map<String, Object> requestProps = request.getRequestProps();
if (requestProps != null) {
// <String, Object> 转扁平化 <String, String>
flatCopyTo("", requestProps, headers);
}
return httpRequest;
}
private static Http2Headers http1HeadersToHttp2Headers(FullHttpRequest request) {
CharSequence host = request.headers().get(HttpHeaderNames.HOST);
Http2Headers http2Headers = new DefaultHttp2Headers()
.method(HttpMethod.GET.asciiName())
.path(request.uri())
.scheme(HttpScheme.HTTP.name());
if (host != null) {
http2Headers.authority(host);
}
return http2Headers;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int defaultClientHeaders() {
Http2Headers headers = new DefaultHttp2Headers(false);
for (int i = 0; i < headerCount; ++i) {
headers.add(headerNames[i], headerValues[i]);
}
headers.method(HttpMethod.POST.asciiName());
headers.scheme(HttpScheme.HTTPS.name());
headers.path(path);
headers.authority(authority);
return iterate(headers);
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
super.handlerAdded(ctx);
// this handler is typically used on an Http2StreamChannel. at this
// stage, ssl handshake should've been established. checking for the
// presence of SslHandler in the parent's channel pipeline to
// determine the HTTP scheme should suffice, even for the case where
// SniHandler is used.
scheme = isSsl(ctx) ? HttpScheme.HTTPS : HttpScheme.HTTP;
}
private static Http2Headers http1HeadersToHttp2Headers(FullHttpRequest request) {
CharSequence host = request.headers().get(HttpHeaderNames.HOST);
Http2Headers http2Headers = new DefaultHttp2Headers()
.method(HttpMethod.GET.asciiName())
.path(request.uri())
.scheme(HttpScheme.HTTP.name());
if (host != null) {
http2Headers.authority(host);
}
return http2Headers;
}
@Test(description = "Test API invocation with an HTTP/1.1 request via insecure connection sending to HTTP/2.0 BE")
public void testHTTP1RequestsViaInsecureConnectionWithHTTP2BE() throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
headers.put(HttpHeaderNames.HOST.toString(), "127.0.0.1:9590");
headers.put(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text().toString(), HttpScheme.HTTP.toString());
headers.put(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.GZIP.toString());
headers.put(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.DEFLATE.toString());
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
log.info("Response: " + response.getResponseMessage() + " , " + response.getResponseCode());
}
@Test(description = "Test API invocation with an HTTP/1.1 request via secure connection sending to HTTP/2.0 BE")
public void testHTTP1RequestsViaSecureConnectionWithHTTP2BE() throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
headers.put(HttpHeaderNames.HOST.toString(), "127.0.0.1:9595");
headers.put(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text().toString(), HttpScheme.HTTP.toString());
headers.put(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.GZIP.toString());
headers.put(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.DEFLATE.toString());
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
log.info("Response: " + response.getResponseMessage() + " , " + response.getResponseCode());
}
private static Http2Headers http1HeadersToHttp2Headers(FullHttpRequest request) {
CharSequence host = request.headers().get(HttpHeaderNames.HOST);
Http2Headers http2Headers = new DefaultHttp2Headers()
.method(HttpMethod.GET.asciiName())
.path(request.uri())
.scheme(HttpScheme.HTTP.name());
if (host != null) {
http2Headers.authority(host);
}
return http2Headers;
}
private static Http2Headers http1HeadersToHttp2Headers(FullHttpRequest request) {
CharSequence host = request.headers().get(HttpHeaderNames.HOST);
Http2Headers http2Headers = new DefaultHttp2Headers()
.method(HttpMethod.GET.asciiName())
.path(request.uri())
.scheme(HttpScheme.HTTP.name());
if (host != null) {
http2Headers.authority(host);
}
return http2Headers;
}
public static FullHttpRequest createGetRequest(String host, int port) {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.valueOf("HTTP/2.0"), HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER);
request.headers()
.add(HttpHeaderNames.HOST, new String(host + ":" + port));
request.headers()
.add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS);
request.headers()
.add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
request.headers()
.add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
return request;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int readOnlyClientHeaders() {
return iterate(ReadOnlyHttp2Headers.clientHeaders(false, HttpMethod.POST.asciiName(), path,
HttpScheme.HTTPS.name(), authority, buildPairs()));
}
public Http2StreamFrameToHttpObjectCodec(final boolean isServer,
final boolean validateHeaders) {
this.isServer = isServer;
this.validateHeaders = validateHeaders;
scheme = HttpScheme.HTTP;
}
H2ToStH1ClientDuplexHandler(boolean sslEnabled, BufferAllocator allocator, HttpHeadersFactory headersFactory,
CloseHandler closeHandler) {
super(allocator, headersFactory, closeHandler);
this.scheme = sslEnabled ? HttpScheme.HTTPS : HttpScheme.HTTP;
}