下面列出了怎么用 io.netty.handler.codec.http.HttpRequest 的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
State state = null;
// Reset the state as each new inbound request comes in.
if (msg instanceof HttpRequest) {
state = createNewState(ctx.channel());
}
// Update the inbound body size with this chunk.
if (msg instanceof HttpContent) {
if (state == null) {
state = getOrCreateCurrentState(ctx.channel());
}
state.inboundBodySize += ((HttpContent) msg).content().readableBytes();
}
super.channelRead(ctx, msg);
}
/**
* Identify the host of an HTTP request. This method uses the URI of the request if possible, otherwise it attempts to find the host
* in the request headers.
*
* @param httpRequest HTTP request to parse the host from
* @return the host the request is connecting to, or null if no host can be found
*/
public static String getHostFromRequest(HttpRequest httpRequest) {
// try to use the URI from the request first, if the URI starts with http:// or https://. checking for http/https avoids confusing
// java's URI class when the request is for a malformed URL like '//some-resource'.
String host = null;
if (startsWithHttpOrHttps(httpRequest.getUri())) {
try {
URI uri = new URI(httpRequest.getUri());
host = uri.getHost();
} catch (URISyntaxException e) {
}
}
// if there was no host in the URI, attempt to grab the host from the Host header
if (host == null || host.isEmpty()) {
host = parseHostHeader(httpRequest, false);
}
return host;
}
protected void captureRequestCookies(HttpRequest httpRequest) {
String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
if (cookieHeader == null) {
return;
}
Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);
for (Cookie cookie : cookies) {
HarCookie harCookie = new HarCookie();
harCookie.setName(cookie.name());
harCookie.setValue(cookie.value());
harEntry.getRequest().getCookies().add(harCookie);
}
}
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
if (httpObject instanceof HttpRequest) {
this.httpRequest = (HttpRequest) httpObject;
}
if (httpObject instanceof HttpContent) {
HttpContent httpContent = (HttpContent) httpObject;
storeRequestContent(httpContent);
if (httpContent instanceof LastHttpContent) {
LastHttpContent lastHttpContent = (LastHttpContent) httpContent;
trailingHeaders = lastHttpContent .trailingHeaders();
}
}
return null;
}
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
if (httpObject instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) httpObject;
if (ProxyUtils.isCONNECT(httpRequest)) {
Attribute<String> hostname = ctx.channel().attr(AttributeKey.valueOf(HOST_ATTRIBUTE_NAME));
String hostAndPort = httpRequest.uri();
// CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
// default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
// would be unexpected.
String hostNoDefaultPort = BrowserUpHttpUtil.removeMatchingPort(hostAndPort, 443);
hostname.set(hostNoDefaultPort);
}
}
return null;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
if (HttpHeaders.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
boolean keepAlive = HttpHeaders.isKeepAlive(req);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
response.headers().set(CONTENT_TYPE, "text/plain");
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, Values.KEEP_ALIVE);
ctx.write(response);
}
}
}
@Override
public void run(String... strings) {
String websocketPath = "/wss";
webScoketServer = new WebSocketServer();
BaseHttpResource httpResource = new HttpResourceThymeleaf();
httpResource.setRootDir("static/websocket/");
httpResource.setDefaultIndexName("websocket.html");
httpResource.setHttpResourceProcess(new HttpResourceProcess() {
@Override
public void porcessResPath(HttpRequest req, String reqPath,
Map<String, Object> reqParameter) {
if (httpResource.getDefaultIndexName().equalsIgnoreCase(reqPath) && (reqParameter != null)) {
reqParameter.put("socketurl", WebSocketUtil.getWebSocketLocation(webScoketServer.getSslCtx() != null, req, websocketPath));
}
}
});
webScoketServer.setHttpResource(httpResource);
webScoketServer.setWebsocketPath(websocketPath);
webScoketServer.setWebSocketEvent(new WebSocketEventChat());
webScoketServer.bind(8989);
NettyLog.info("websocket server run end ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LOGGER.info("[Client ({})] => [Server ({})] : {}",
connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
msg);
if (msg instanceof FullHttpRequest) {
String streamId = ((HttpRequest) msg).headers().get(
HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
if (streamId == null) {
throw new IllegalStateException("No streamId");
}
streams.offer(streamId);
} else if (msg instanceof HttpObject) {
throw new IllegalStateException("Cannot handle message: " + msg.getClass());
}
outboundChannel.writeAndFlush(msg);
}
@Override
public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
for (EventDetector eventDetector: eventDetectors) {
if (eventDetector.canDetectPredicate().test(httpRequest)) {
try {
Optional<Map<String, String>> optionalEvent = eventDetector.getConverter().convert(httpRequest);
if (optionalEvent.isPresent()) {
Map<String, String> event = optionalEvent.get();
recordingState.storeTestCaseStep(event);
logger.info("Recorded event {}", event);
}
} catch (UnsupportedEncodingException | MalformedURLException e) {
logger.error("Error while trying to convert test case step", e);
}
}
}
return null;
}
@Test(
alwaysRun = true,
dependsOnMethods = {"testMetricManager"})
public void testInvalidRootRequest() throws InterruptedException {
Channel channel = TestUtils.connect(false, configManager);
Assert.assertNotNull(channel);
HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
channel.writeAndFlush(req).sync();
channel.closeFuture().sync();
ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);
Assert.assertEquals(resp.getCode(), HttpResponseStatus.METHOD_NOT_ALLOWED.code());
Assert.assertEquals(resp.getMessage(), ERROR_METHOD_NOT_ALLOWED);
}
protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason)
{
// Only allow this method to run once per request.
Attribute<State> attr = ctx.channel().attr(ATTR_STATE);
State state = attr.get();
if (state == null || state != State.STARTED)
return false;
attr.set(State.COMPLETED);
HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get();
HttpResponse response = ctx.channel().attr(ATTR_HTTP_RESP).get();
// Cleanup channel attributes.
ctx.channel().attr(ATTR_HTTP_REQ).set(null);
ctx.channel().attr(ATTR_HTTP_RESP).set(null);
// Fire the event to whole pipeline.
ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response));
return true;
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
{
State state = null;
// Reset the state as each new outbound request goes out.
if (msg instanceof HttpRequest) {
state = createNewState(ctx.channel());
}
// Update the outbound body size with this chunk.
if (msg instanceof HttpContent) {
if (state == null) {
state = getOrCreateCurrentState(ctx.channel());
}
state.outboundBodySize += ((HttpContent) msg).content().readableBytes();
}
super.write(ctx, msg, promise);
}
@Test
public void acceptsMalformedCookiesWithRelaxedValidation() {
HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http://foo.com/");
request.headers().set(HOST, "http://foo.com/");
request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=a,b");
NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder()
.uniqueIdSupplier(uniqueIdSupplier)
.build();
LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty())
.build();
LiveHttpRequest expected = new LiveHttpRequest.Builder(
HttpMethod.GET, "http://foo.com/")
.cookies(
requestCookie("ABC01", "\"1\""),
requestCookie("ABC02", "1"),
requestCookie("guid", "a,b")
)
.build();
assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies())));
}
@Test(
alwaysRun = true,
dependsOnMethods = {"testDescribeModelNotFound"})
public void testRegisterModelMissingUrl() throws InterruptedException {
Channel channel = TestUtils.connect(true, configManager);
Assert.assertNotNull(channel);
HttpRequest req =
new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/models");
channel.writeAndFlush(req).sync();
channel.closeFuture().sync();
ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);
Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code());
Assert.assertEquals(resp.getMessage(), "Parameter url is required.");
}
/**
* Checks the headers in the response match those in the request.
* @param request the {@link HttpRequest} with the original value of the headers.
* @param response the {@link HttpResponse} that should have the same value for some headers in {@code request}.
* @throws ParseException
*/
private void checkHeaders(HttpRequest request, HttpResponse response) throws ParseException {
assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.status());
assertEquals(HttpHeaderNames.CONTENT_TYPE + " does not match", request.headers().get(HttpHeaderNames.CONTENT_TYPE),
response.headers().get(HttpHeaderNames.CONTENT_TYPE));
assertEquals(HttpHeaderNames.CONTENT_LENGTH + " does not match",
request.headers().get(HttpHeaderNames.CONTENT_LENGTH), response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertEquals(HttpHeaderNames.LOCATION + " does not match", request.headers().get(HttpHeaderNames.LOCATION),
response.headers().get(HttpHeaderNames.LOCATION));
assertEquals(HttpHeaderNames.LAST_MODIFIED + " does not match",
request.headers().getTimeMillis(HttpHeaderNames.LAST_MODIFIED),
response.headers().getTimeMillis(HttpHeaderNames.LAST_MODIFIED));
assertEquals(HttpHeaderNames.EXPIRES + " does not match", request.headers().getTimeMillis(HttpHeaderNames.EXPIRES),
response.headers().getTimeMillis(HttpHeaderNames.EXPIRES));
assertEquals(HttpHeaderNames.CACHE_CONTROL + " does not match",
request.headers().get(HttpHeaderNames.CACHE_CONTROL), response.headers().get(HttpHeaderNames.CACHE_CONTROL));
assertEquals(HttpHeaderNames.PRAGMA + " does not match", request.headers().get(HttpHeaderNames.PRAGMA),
response.headers().get(HttpHeaderNames.PRAGMA));
assertEquals(HttpHeaderNames.DATE + " does not match", request.headers().getTimeMillis(HttpHeaderNames.DATE),
response.headers().getTimeMillis(HttpHeaderNames.DATE));
assertEquals(MockNettyMessageProcessor.CUSTOM_HEADER_NAME + " does not match",
request.headers().get(MockNettyMessageProcessor.CUSTOM_HEADER_NAME),
response.headers().get(MockNettyMessageProcessor.CUSTOM_HEADER_NAME));
}
@Test
public void alternate_constructor_creates_instance_using_specified_wingtips_strategy_and_adapter() {
// given
HttpTagAndSpanNamingStrategy<HttpRequest, HttpResponse> wingtipsStrategyMock =
mock(HttpTagAndSpanNamingStrategy.class);
HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> wingtipsAdapterMock =
mock(HttpTagAndSpanNamingAdapter.class);
// when
DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy instance =
new DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy(wingtipsStrategyMock, wingtipsAdapterMock);
// then
assertThat(instance.tagAndNamingStrategy).isSameAs(wingtipsStrategyMock);
assertThat(instance.tagAndNamingAdapter).isSameAs(wingtipsAdapterMock);
}
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
if (httpObject instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) httpObject;
if (ProxyUtils.isCONNECT(httpRequest)) {
Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME));
String hostAndPort = httpRequest.getUri();
// CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
// default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
// would be unexpected.
String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443);
hostname.set(hostNoDefaultPort);
}
}
return null;
}
@Override
public void channelRead0(final ChannelHandlerContext ctx,
final HttpRequest req) throws Exception {
Preconditions.checkArgument(req.getUri().startsWith(WEBHDFS_PREFIX));
QueryStringDecoder queryString = new QueryStringDecoder(req.getUri());
params = new ParameterParser(queryString, conf);
DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
ugi = ugiProvider.ugi();
path = params.path();
injectToken();
ugi.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
handle(ctx, req);
return null;
}
});
}
/**
* Copy the headers part of Netty Request to OData Request
* @param odRequest
* @param req
*/
static void copyHeaders(ODataRequest odRequest, final HttpRequest req) {
final Set<String> headers = req.headers().names();
Iterator<String> headerNames = headers.iterator();
while (headerNames.hasNext()) {
final String headerName = headerNames.next();
final List<String> headerValues = req.headers().getAll(headerName);
odRequest.addHeader(headerName, headerValues);
}
}
/**
* Resolves the request to an application by mapping the request url to the application path.
*
* @param request
* @return the application that this request resolves to
*/
public Application<ApplicationConfiguration> resolve(HttpRequest request) {
String path = request.getUri();
for (Entry<String, Application<ApplicationConfiguration>> entry : getSortedApplications().entrySet()) {
if (path.startsWith(entry.getKey())) {
return entry.getValue();
}
}
return null;
}
@Test
public void getRequestInfo_creates_new_RequestInfo_based_on_msg_if_state_requestInfo_is_null_and_msg_is_a_HttpRequest() {
// given
assertThat(state.getRequestInfo(), nullValue());
String expectedUri = "/some/uri/" + UUID.randomUUID().toString();
HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, expectedUri);
// when
RequestInfo<?> result = handler.getRequestInfo(state, httpRequest);
// then
assertThat(result.getUri(), is(expectedUri));
}
public ConnectionFlowProcessor(ChannelMediator channelMediator, HttpRequest httpRequest,
List<ConnectionFlowStep> connectionFlow) {
_channelMediator = channelMediator;
_connectionFlow = connectionFlow;
_complete = false;
_startTime = System.currentTimeMillis();
_remoteAddress = getRemoteAddress(httpRequest);
LOG.debug(String.format("Start connection flow at: %d", _startTime));
}
private void testLoadModel(Channel channel) throws InterruptedException {
result = null;
latch = new CountDownLatch(1);
HttpRequest req =
new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1,
HttpMethod.POST,
"/models?url=noop-v0.1&model_name=noop_v0.1&runtime=python&synchronous=false");
channel.writeAndFlush(req);
latch.await();
StatusResponse resp = JsonUtils.GSON.fromJson(result, StatusResponse.class);
Assert.assertEquals(resp.getStatus(), "Model \"noop_v0.1\" registered");
}
public boolean denied(HttpRequest request) {
for (Http1DeterministicRuleEngineConfig.Rule rule : blacklist) {
if (rule.matches(request)) {
return true;
}
}
return false;
}
@Override
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession sslSession) {
String requestedHostname = HttpUtil.getHostFromRequest(httpRequest);
try {
SslContext ctx = getHostnameImpersonatingSslContext(requestedHostname, sslSession);
return ctx.newEngine(ByteBufAllocator.DEFAULT);
} catch (RuntimeException e) {
throw new MitmException("Error creating SSLEngine for connection to client to impersonate upstream host: " + requestedHostname, e);
}
}
/**
* Gets the host and port from the specified request. Returns the host and port from the request URI if available,
* otherwise retrieves the host and port from the Host header.
*
* @param httpRequest HTTP request
* @return host and port of the request
*/
public static String getHostAndPortFromRequest(HttpRequest httpRequest) {
if (startsWithHttpOrHttps(httpRequest.uri())) {
try {
return getHostAndPortFromUri(httpRequest.uri());
} catch (URISyntaxException e) {
// the URI could not be parsed, so return the host and port in the Host header
}
}
return parseHostHeader(httpRequest, true);
}
public static HttpRequest successful() {
return new WebSocketRequestBuilder().httpVersion(HTTP_1_1)
.method(HttpMethod.GET)
.uri("/test")
.host("server.example.com")
.upgrade(HttpHeaderValues.WEBSOCKET)
.key("dGhlIHNhbXBsZSBub25jZQ==")
.origin("http://example.com")
.version13()
.build();
}
@Test
public void callsTheEscaperForUnwiseChars() {
UnwiseCharsEncoder encoder = mock(UnwiseCharsEncoder.class);
NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder()
.uniqueIdSupplier(uniqueIdSupplier)
.unwiseCharEncoder(encoder)
.build();
HttpRequest request = newHttpRequest("/foo");
when(encoder.encode("/foo")).thenReturn("/foo");
request.headers().add(HOST, "example.com");
handle(request, decoder);
verify(encoder).encode("/foo");
}
/**
* 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);
}
public HttpsOriginalHostCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx) {
super(originalRequest, ctx);
// if this is an HTTP CONNECT, set the isHttps attribute on the ChannelHandlerConect and capture the hostname from the original request.
// capturing the original host (and the remapped/modified host in clientToProxyRequest() below) guarantees that we will
// have the "true" host, rather than relying on the Host header in subsequent requests (which may be absent or spoofed by malicious clients).
if (ProxyUtils.isCONNECT(originalRequest)) {
Attribute<String> originalHostAttr = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.ORIGINAL_HOST_ATTRIBUTE_NAME));
String hostAndPort = originalRequest.getUri();
originalHostAttr.set(hostAndPort);
Attribute<Boolean> isHttpsAttr = ctx.attr(AttributeKey.<Boolean>valueOf(HttpsAwareFiltersAdapter.IS_HTTPS_ATTRIBUTE_NAME));
isHttpsAttr.set(true);
}
}