下面列出了io.netty.channel.DefaultEventLoop#io.netty.handler.codec.http.DefaultHttpRequest 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected HttpMessage createMessage(final String[] initialLine)
throws Exception {
// If the first element of the initial line is a version string then
// this is a response
if (versionPattern.matcher(initialLine[0]).matches()) {
isDecodingRequest = false;
return new DefaultHttpResponse(RtspVersions.valueOf(initialLine[0]),
new HttpResponseStatus(Integer.parseInt(initialLine[1]),
initialLine[2]),
validateHeaders);
} else {
isDecodingRequest = true;
return new DefaultHttpRequest(RtspVersions.valueOf(initialLine[2]),
RtspMethods.valueOf(initialLine[0]),
initialLine[1],
validateHeaders);
}
}
@Test
public void testFormEncodeIncorrect() throws Exception {
LastHttpContent content = new DefaultLastHttpContent(
Unpooled.copiedBuffer("project=netty&&project=netty", CharsetUtil.US_ASCII));
DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
try {
decoder.offer(content);
fail();
} catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
assertTrue(e.getCause() instanceof IllegalArgumentException);
} finally {
decoder.destroy();
content.release();
}
}
/**
* Create a new object to contain the request data.
*
* @param streamId The stream associated with the request
* @param http2Headers The initial set of HTTP/2 headers to create the request with
* @param validateHttpHeaders <ul>
* <li>{@code true} to validate HTTP headers in the http-codec</li>
* <li>{@code false} not to validate HTTP headers in the http-codec</li>
* </ul>
* @return A new request object which represents headers for a chunked request
* @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
*/
public static HttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders)
throws Http2Exception {
// HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
final CharSequence method = checkNotNull(http2Headers.method(),
"method header cannot be null in conversion to HTTP/1.x");
final CharSequence path = checkNotNull(http2Headers.path(),
"path header cannot be null in conversion to HTTP/1.x");
HttpRequest msg = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method.toString()),
path.toString(), validateHttpHeaders);
try {
addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true);
} catch (Http2Exception e) {
throw e;
} catch (Throwable t) {
throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
}
return msg;
}
@Test
public void testEncodeRequestHeaders() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world");
assertTrue(ch.writeOutbound(request));
Http2HeadersFrame headersFrame = ch.readOutbound();
Http2Headers headers = headersFrame.headers();
assertThat(headers.scheme().toString(), is("http"));
assertThat(headers.method().toString(), is("GET"));
assertThat(headers.path().toString(), is("/hello/world"));
assertFalse(headersFrame.isEndStream());
assertThat(ch.readOutbound(), is(nullValue()));
assertFalse(ch.finish());
}
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().toString(), httpRequest.uri(),
httpHeadsInfo, null);
}
return httpRequest;
}
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;
}
@Test
public void shouldTransformStyxRequestToNettyRequestWithAllRelevantInformation() {
LiveHttpRequest request = new LiveHttpRequest.Builder()
.method(GET)
.header("X-Forwarded-Proto", "https")
.cookies(
requestCookie("HASESSION_V3", "asdasdasd"),
requestCookie("has", "123456789")
)
.uri("https://www.example.com/foo%2Cbar?foo,baf=2")
.build();
DefaultHttpRequest nettyRequest = HttpRequestOperation.toNettyRequest(request);
assertThat(nettyRequest.method(), is(io.netty.handler.codec.http.HttpMethod.GET));
assertThat(nettyRequest.uri(), is("https://www.example.com/foo%2Cbar?foo%2Cbaf=2"));
assertThat(nettyRequest.headers().get("X-Forwarded-Proto"), is("https"));
assertThat(ServerCookieDecoder.LAX.decode(nettyRequest.headers().get("Cookie")),
containsInAnyOrder(
new DefaultCookie("HASESSION_V3", "asdasdasd"),
new DefaultCookie("has", "123456789")));
}
@Test
public void shouldTransformUrlQueryParametersToNettyRequest() {
LiveHttpRequest request = new LiveHttpRequest.Builder()
.method(GET)
.header("X-Forwarded-Proto", "https")
.uri("https://www.example.com/foo?some=value&blah=blah")
.build();
LiveHttpRequest.Transformer builder = request.newBuilder();
LiveHttpRequest newRequest = builder.url(
request.url().newBuilder()
.addQueryParam("format", "json")
.build())
.build();
DefaultHttpRequest nettyRequest = HttpRequestOperation.toNettyRequest(newRequest);
assertThat(nettyRequest.method(), is(io.netty.handler.codec.http.HttpMethod.GET));
assertThat(nettyRequest.uri(), is("https://www.example.com/foo?some=value&blah=blah&format=json"));
assertThat(nettyRequest.headers().get("X-Forwarded-Proto"), is("https"));
}
/**
* Configures the headers in the specified Netty HTTP request.
*/
private void addHeadersToRequest(DefaultHttpRequest httpRequest, SdkHttpRequest request) {
httpRequest.headers().add(HOST, getHostHeaderValue(request));
String scheme = request.getUri().getScheme();
if (Protocol.HTTP2 == protocol && !StringUtils.isBlank(scheme)) {
httpRequest.headers().add(ExtensionHeaderNames.SCHEME.text(), scheme);
}
// Copy over any other headers already in our request
request.headers().entrySet().stream()
/*
* Skip the Host header to avoid sending it twice, which will
* interfere with some signing schemes.
*/
.filter(e -> !IGNORE_HEADERS.contains(e.getKey()))
.forEach(e -> e.getValue().forEach(h -> httpRequest.headers().add(e.getKey(), h)));
}
/**
* Helper method that generates a {@link HttpRequest} for the downstream call's first chunk that uses the given
* downstreamPath and downstreamMethod, and the query string and headers from the incomingRequest will be added and
* passed through without modification.
*/
@SuppressWarnings("UnusedParameters")
protected @NotNull HttpRequest generateSimplePassthroughRequest(
@NotNull RequestInfo<?> incomingRequest,
@NotNull String downstreamPath,
@NotNull HttpMethod downstreamMethod,
@NotNull ChannelHandlerContext ctx
) {
String queryString = extractQueryString(incomingRequest.getUri());
String downstreamUri = downstreamPath;
// TODO: Add logic to support when downstreamPath already has a query string on it. The two query strings should be combined
if (queryString != null)
downstreamUri += queryString;
HttpRequest downstreamRequestInfo =
new DefaultHttpRequest(HttpVersion.HTTP_1_1, downstreamMethod, downstreamUri);
downstreamRequestInfo.headers().set(incomingRequest.getHeaders());
return downstreamRequestInfo;
}
@Test
public void getRequestInfo_uses_dummy_instance_if_an_exception_occurs_while_creating_RequestInfo_from_HttpRequest_msg() {
// given
assertThat(state.getRequestInfo(), nullValue());
RiposteHandlerInternalUtil explodingHandlerUtilMock = mock(RiposteHandlerInternalUtil.class);
doThrow(new RuntimeException("intentional exception"))
.when(explodingHandlerUtilMock)
.createRequestInfoFromNettyHttpRequestAndHandleStateSetupIfNecessary(any(), any());
Whitebox.setInternalState(handler, "handlerUtils", explodingHandlerUtilMock);
HttpRequest httpRequest = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/uri"
);
// when
RequestInfo<?> result = handler.getRequestInfo(state, httpRequest);
// then
assertThat(result.getUri(), is(RequestInfo.NONE_OR_UNKNOWN_TAG));
verify(explodingHandlerUtilMock)
.createRequestInfoFromNettyHttpRequestAndHandleStateSetupIfNecessary(httpRequest, state);
}
@SuppressWarnings("FutureReturnValueIgnored")
private void doTestStatus(HttpResponseStatus status) {
EmbeddedChannel channel = new EmbeddedChannel();
HttpServerOperations ops = new HttpServerOperations(
Connection.from(channel),
ConnectionObserver.emptyListener(),
null,
new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"),
null,
ServerCookieEncoder.STRICT,
ServerCookieDecoder.STRICT);
ops.status(status);
HttpMessage response = ops.newFullBodyMessage(Unpooled.EMPTY_BUFFER);
assertThat(((FullHttpResponse) response).status().reasonPhrase()).isEqualTo(status.reasonPhrase());
// "FutureReturnValueIgnored" is suppressed deliberately
channel.close();
}
/**
* Tests that the client converts given {@link FullHttpRequest} to bytes, which is sent to the
* server and reconstructed to a {@link FullHttpRequest} that is equivalent to the original. Then
* test that the server converts given {@link FullHttpResponse} to bytes, which is sent to the
* client and reconstructed to a {@link FullHttpResponse} that is equivalent to the original.
*
* <p>The request and response equivalences are tested in the same method because the client codec
* tries to pair the response it receives with the request it sends. Receiving a response without
* sending a request first will cause the {@link HttpObjectAggregator} to fail to aggregate
* properly.
*/
private void requestAndRespondWithStatus(HttpResponseStatus status) {
ByteBuf buffer;
FullHttpRequest requestSent = makeHttpGetRequest(HOST, PATH);
// Need to send a copy as the content read index will advance after the request is written to
// the outbound of client channel, making comparison with requestReceived fail.
assertThat(clientChannel.writeOutbound(requestSent.copy())).isTrue();
buffer = clientChannel.readOutbound();
assertThat(channel.writeInbound(buffer)).isTrue();
// We only have a DefaultHttpRequest, not a FullHttpRequest because there is no HTTP aggregator
// in the server's pipeline. But it is fine as we are not interested in the content (payload) of
// the request, just its headers, which are contained in the DefaultHttpRequest.
DefaultHttpRequest requestReceived = channel.readInbound();
// Verify that the request received is the same as the request sent.
assertHttpRequestEquivalent(requestSent, requestReceived);
FullHttpResponse responseSent = makeHttpResponse(status);
assertThat(channel.writeOutbound(responseSent.copy())).isTrue();
buffer = channel.readOutbound();
assertThat(clientChannel.writeInbound(buffer)).isTrue();
FullHttpResponse responseReceived = clientChannel.readInbound();
// Verify that the request received is the same as the request sent.
assertHttpResponseEquivalent(responseSent, responseReceived);
}
@BeforeMethod
public void setUp() throws Exception {
HttpCarbonMessage httpCarbonMessage = new HttpCarbonMessage(
new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j"));
httpCarbonMessage.getHeaders().add("testA", "test1");
httpCarbonMessage.getHeaders().add("testA", "test2");
httpCarbonMessage.setHeader("Accept", "application/json");
httpCarbonMessage.setHeader("Content-Type", "text/html");
httpCarbonMessage.setHeader("Content-Language", "en");
httpCarbonMessage.setHeader("Content-Length", "1024");
httpCarbonMessage.setHeader("Date", "Sun, 06 Nov 1994 08:49:37 GMT");
httpCarbonMessage.getHeaders().add("Accept-Language", "da");
httpCarbonMessage.getHeaders().add("Accept-Language", "en-gb;q=0.8");
httpCarbonMessage.getHeaders().add("Accept-Language", "en;q=0.7");
httpCarbonMessage.getHeaders().add("Cookie", "JSESSIONID=3508015E4EF0ECA8C4B761FCC4BC1718");
httpHeaders1 = new HttpHeadersImpl(httpCarbonMessage.getHeaders());
HttpCarbonMessage httpCarbonMessage2 = new HttpCarbonMessage(
new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j"));
httpHeaders2 = new HttpHeadersImpl(httpCarbonMessage2.getHeaders());
}
@Test
public void testDeniedRule() throws UnknownHostException {
List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>();
HashMultimap<String, String> headers = HashMultimap.create();
headers.put("User-Agent", "Bad-actor: 1.0");
Http1DeterministicRuleEngineConfig.Rule bad =
new Http1DeterministicRuleEngineConfig.Rule(
HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers);
blacklist.add(bad);
Http1Filter http1Filter =
new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist)));
EmbeddedChannel chDeny = new EmbeddedChannel(http1Filter);
DefaultHttpRequest request =
new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure");
request.headers().set("User-Agent", "Bad-actor: 1.0");
chDeny.writeInbound(request);
chDeny.runPendingTasks();
assertFalse(chDeny.isActive());
assertFalse(chDeny.isOpen());
}
@Test
public void testAllowedRule() throws UnknownHostException {
List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>();
HashMultimap<String, String> headers = HashMultimap.create();
headers.put("User-Agent", "Bad-actor: 1.0");
Http1DeterministicRuleEngineConfig.Rule bad =
new Http1DeterministicRuleEngineConfig.Rule(
HttpMethod.POST, "/path/to/failure", HttpVersion.HTTP_1_1, headers);
blacklist.add(bad);
Http1Filter http1Filter =
new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist)));
EmbeddedChannel chAllow = new EmbeddedChannel(http1Filter);
DefaultHttpRequest request =
new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure");
request.headers().set("User-Agent", "Bad-actor: 1.0");
chAllow.writeInbound(request);
assertTrue(chAllow.isActive());
assertTrue(chAllow.isOpen());
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
negotiationLogger(ctx).log(ChannelLogLevel.INFO, "Http2Upgrade started");
HttpClientCodec httpClientCodec = new HttpClientCodec();
ctx.pipeline().addBefore(ctx.name(), null, httpClientCodec);
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(next);
HttpClientUpgradeHandler upgrader =
new HttpClientUpgradeHandler(httpClientCodec, upgradeCodec, /*maxContentLength=*/ 1000);
ctx.pipeline().addBefore(ctx.name(), null, upgrader);
// Trigger the HTTP/1.1 plaintext upgrade protocol by issuing an HTTP request
// which causes the upgrade headers to be added
DefaultHttpRequest upgradeTrigger =
new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
upgradeTrigger.headers().add(HttpHeaderNames.HOST, authority);
ctx.writeAndFlush(upgradeTrigger).addListener(
ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
super.handlerAdded(ctx);
}
/**
* Creates a {@link NettyRequest} with the given parameters.
* @param httpMethod the {@link HttpMethod} desired.
* @param uri the URI desired.
* @param headers {@link HttpHeaders} that need to be a part of the request.
* @param channel the {@link Channel} that the request arrived over.
* @return {@link NettyRequest} encapsulating a {@link HttpRequest} with the given parameters.
* @throws RestServiceException if the {@code httpMethod} is not recognized by {@link NettyRequest}.
*/
private NettyRequest createNettyRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, Channel channel)
throws RestServiceException {
MetricRegistry metricRegistry = new MetricRegistry();
RestRequestMetricsTracker.setDefaults(metricRegistry);
HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, false);
if (headers != null) {
httpRequest.headers().set(headers);
}
NettyRequest nettyRequest =
new NettyRequest(httpRequest, channel, new NettyMetrics(metricRegistry), BLACKLISTED_QUERY_PARAM_SET);
assertEquals("Auto-read is in an invalid state",
(!httpMethod.equals(HttpMethod.POST) && !httpMethod.equals(HttpMethod.PUT))
|| NettyRequest.bufferWatermark <= 0, channel.config().isAutoRead());
return nettyRequest;
}
@Test
public void testNotNoHbaConfig() throws Exception {
HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
EmbeddedChannel ch = new EmbeddedChannel(handler);
DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
request.headers().add(HttpHeaderNames.AUTHORIZATION.toString(), "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
request.headers().add("X-Real-Ip", "10.1.0.100");
ch.writeInbound(request);
ch.releaseInbound();
assertFalse(handler.authorized());
assertUnauthorized(
ch.readOutbound(),
"No valid auth.host_based.config entry found for host \"10.1.0.100\", user \"Aladdin\", protocol \"http\"\n");
}
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Trigger the HTTP/1.1 plaintext upgrade protocol by issuing an HTTP request
// which causes the upgrade headers to be added
DefaultHttpRequest upgradeTrigger =
new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
ctx.writeAndFlush(upgradeTrigger);
super.channelActive(ctx);
}
@Setup(Level.Trial)
public void setup() {
byte[] bytes = new byte[256];
content = Unpooled.buffer(bytes.length);
content.writeBytes(bytes);
ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
HttpHeaders headersWithChunked = new DefaultHttpHeaders(false);
headersWithChunked.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
HttpHeaders headersWithContentLength = new DefaultHttpHeaders(false);
headersWithContentLength.add(HttpHeaderNames.CONTENT_LENGTH, testContent.readableBytes());
fullRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", testContent,
headersWithContentLength, EmptyHttpHeaders.INSTANCE);
contentLengthRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index",
headersWithContentLength);
chunkedRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", headersWithChunked);
lastContent = new DefaultLastHttpContent(testContent, false);
encoder = new HttpRequestEncoder();
context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
UnpooledByteBufAllocator.DEFAULT, encoder) {
@Override
protected void handleException(Throwable t) {
handleUnexpectedException(t);
}
};
}
public static HttpRequest newUpgradeRequest(String ext) {
HttpRequest req = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/chat");
req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET.toString().toLowerCase());
req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
if (ext != null) {
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, ext);
}
return req;
}
/**
* Test of a SETUP request, with no body.
*/
@Test
public void testSendSetupRequest() {
String expected = "SETUP rtsp://172.10.20.30:554/d3abaaa7-65f2-42b4-"
+ "8d6b-379f492fcf0f RTSP/1.0\r\n"
+ "transport: MP2T/DVBC/UDP;unicast;client=01234567;"
+ "source=172.10.20.30;"
+ "destination=1.1.1.1;client_port=6922\r\n"
+ "cseq: 1\r\n"
+ "\r\n";
HttpRequest request = new DefaultHttpRequest(RtspVersions.RTSP_1_0,
RtspMethods.SETUP,
"rtsp://172.10.20.30:554/d3abaaa7-65f2-42b4-8d6b-379f492fcf0f");
request.headers().add(RtspHeaderNames.TRANSPORT,
"MP2T/DVBC/UDP;unicast;client=01234567;source=172.10.20.30;" +
"destination=1.1.1.1;client_port=6922");
request.headers().add(RtspHeaderNames.CSEQ, "1");
EmbeddedChannel ch = new EmbeddedChannel(new RtspEncoder());
ch.writeOutbound(request);
ByteBuf buf = ch.readOutbound();
String actual = buf.toString(CharsetUtil.UTF_8);
buf.release();
assertEquals(expected, actual);
}
/**
* Copy the given {@link HttpRequest} verbatim.
*
* @param original
* @return
*/
private HttpRequest copy(HttpRequest original) {
if (original instanceof FullHttpRequest) {
return ((FullHttpRequest) original).copy();
} else {
HttpRequest request = new DefaultHttpRequest(original.getProtocolVersion(),
original.getMethod(), original.getUri());
request.headers().set(original.headers());
return request;
}
}
@Override
protected HttpMessage createMessage(String[] initialLine) throws Exception {
return isDecodingRequest() ? new DefaultHttpRequest(
HttpVersion.valueOf(initialLine[2]),
HttpMethod.valueOf(initialLine[0]), initialLine[1], validateHeaders) :
new DefaultHttpResponse(
HttpVersion.valueOf(initialLine[0]),
HttpResponseStatus.valueOf(Integer.parseInt(initialLine[1]), initialLine[2]), validateHeaders);
}
public static void main(String[] args) {
NettyHttpClient client=new NettyHttpClient();
long time=System.currentTimeMillis();
HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/baidu?tn=monline_6_dg&ie=utf-8&wd=netty+http客户端");
HttpResponse response=client.syncRequest("www.baidu.com", 80, request);
System.out.println(System.currentTimeMillis()-time);
System.out.println(response);
FullHttpResponse rsp=(FullHttpResponse) response;
System.out.println("content:"+rsp.content().toString(CharsetUtil.UTF_8));
// new Scanner(System.in).nextLine();
}
@VisibleForTesting
static DefaultHttpRequest toNettyRequest(LiveHttpRequest request) {
HttpVersion version = request.version();
HttpMethod method = request.method();
String url = request.url().toString();
DefaultHttpRequest nettyRequest = new DefaultHttpRequest(toNettyVersion(version), toNettyMethod(method), url, true);
request.headers().forEach((name, value) ->
nettyRequest.headers().add(name, value));
return nettyRequest;
}
private io.netty.handler.codec.http.HttpRequest makeRequest(LiveHttpRequest request) {
DefaultHttpRequest nettyRequest = toNettyRequest(request);
Optional<String> host = request.header(HOST);
if (!host.isPresent()) {
nettyRequest.headers().set(HOST, nettyConnection.getOrigin().hostAndPortString());
}
return nettyRequest;
}
@BeforeEach
public void setUp() {
channel = createEmbeddedChannel(newHttpRequestDecoderWithFlowControl());
chunkedRequestHeaders = new DefaultHttpRequest(HTTP_1_1, POST, "/foo/bar");
chunkedRequestHeaders.headers().set(TRANSFER_ENCODING, CHUNKED);
chunkedRequestHeaders.headers().set(HOST, "foo.com");
bodyCompletedLatch = new CountDownLatch(1);
}
public HttpRequest adapt(SdkHttpRequest sdkRequest) {
HttpMethod method = toNettyHttpMethod(sdkRequest.method());
HttpHeaders headers = new DefaultHttpHeaders();
String uri = encodedPathAndQueryParams(sdkRequest);
// All requests start out as HTTP/1.1 objects, even if they will
// ultimately be sent over HTTP2. Conversion to H2 is handled at a
// later stage if necessary; see HttpToHttp2OutboundAdapter.
DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers);
addHeadersToRequest(request, sdkRequest);
return request;
}