下面列出了 io.netty.handler.codec.http.HttpRequest # uri ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
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;
}
@Override
public boolean accept(ChannelHandlerContext ctx, HttpRequest req) {
if (req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri)) {
try {
User superAdmin = AuthHeadersBaseHttpHandler.validateAuth(userDao, req);
if (superAdmin != null) {
ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).set(superAdmin);
queryStringDecoder = new QueryStringDecoder(req.uri());
return true;
}
} catch (IllegalAccessException e) {
//return 403 and stop processing.
ctx.writeAndFlush(Response.forbidden(e.getMessage()));
return true;
}
}
return false;
}
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) {
if (isWebSocketRequest(req)) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.uri(), null, true);
this.handshaker = wsFactory.newHandshaker(req);
if (this.handshaker == null) {
//Return that we need cannot not support the web socket version
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
this.handshaker.handshake(ctx.channel(), req);
this.session = new WebSocketSession(ctx);
this.uri = req.uri();
initHandlerWrapper();
//Allows the user to send messages in the event of onConnect
CompletableFuture.completedFuture(new WebSocketContext(this.session,this.handler))
.thenAcceptAsync(this.handler::onConnect,ctx.executor());
}
} else {
ReferenceCountUtil.retain(req);
ctx.fireChannelRead(req);
}
}
/**
* 检测url是否匹配
*/
public static boolean checkUrl(HttpRequest httpRequest, String regex) {
String host = httpRequest.headers().get(HttpHeaderNames.HOST);
if (host != null && regex != null) {
String url;
if (httpRequest.uri().indexOf("/") == 0) {
if (httpRequest.uri().length() > 1) {
url = host + httpRequest.uri();
} else {
url = host;
}
} else {
url = httpRequest.uri();
}
return url.matches(regex);
}
return false;
}
private String getWebSocketLocation(HttpRequest req) {
String protocol = secure ? "wss://" : "ws://";
String webSocketLocation = protocol + req.headers().get(HttpHeaderNames.HOST) + req.uri();
if (log.isDebugEnabled())
log.debug("Created {} at: {}", getTransportType().getName(), webSocketLocation);
return webSocketLocation;
}
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);
}
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.channel().attr(AttributeKey.valueOf(ORIGINAL_HOST_ATTRIBUTE_NAME));
String hostAndPort = originalRequest.uri();
originalHostAttr.set(hostAndPort);
Attribute<Boolean> isHttpsAttr = ctx.channel().attr(AttributeKey.valueOf(IS_HTTPS_ATTRIBUTE_NAME));
isHttpsAttr.set(true);
}
}
public Session(String remoteIp, HttpRequest request) {
this.remoteIp = remoteIp;
this.uri = request.uri();
if (request.decoderResult().isSuccess()) {
method = request.method().name();
protocol = request.protocolVersion().text();
} else {
method = "GET";
protocol = "HTTP/1.1";
}
requestId = UUID.randomUUID().toString();
startTime = System.currentTimeMillis();
}
/**
* 一般是针对get请求的
* @param request get请求对象
*/
public AuthRequest(HttpRequest request) {
if (request.uri() != null) {
QueryStringDecoder dec = new QueryStringDecoder(request.uri());
Map<String, List<String>> params = dec.parameters();
this.clientId = QueryParameter.getFirstElement(params, CLIENT_ID);
this.responseType = QueryParameter.getFirstElement(params, RESPONSE_TYPE);
this.redirectUri = QueryParameter.getFirstElement(params, REDIRECT_URI);
this.state = QueryParameter.getFirstElement(params, STATE);
this.scope = QueryParameter.getFirstElement(params, SCOPE);
this.userId = QueryParameter.getFirstElement(params, USER_ID);
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = currentMessage = (HttpRequest) msg;
String uri = request.uri();
if (!uri.startsWith(BLOBS_ENDPOINT)) {
reset();
ctx.fireChannelRead(msg);
return;
}
Matcher matcher = blobsMatcher.reset(uri);
if (!matcher.matches()) {
simpleResponse(request, HttpResponseStatus.NOT_FOUND);
return;
}
digestBlob = null;
index = BlobIndex.fullIndexName(matcher.group(1));
digest = matcher.group(2);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("matches index:{} digest:{}", index, digest);
LOGGER.trace("HTTPMessage:%n{}", request);
}
handleBlobRequest(request, null);
} else if (msg instanceof HttpContent) {
if (currentMessage == null) {
// the chunk is probably from a regular non-blob request.
reset();
ctx.fireChannelRead(msg);
return;
}
handleBlobRequest(currentMessage, (HttpContent) msg);
} else {
// Neither HttpMessage or HttpChunk
reset();
ctx.fireChannelRead(msg);
}
}
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (this.logger.isEnabled(this.internalLevel)) {
HttpRequest request = (HttpRequest) msg;
String log = request.method() + " " + request.uri() + " " + request.protocolVersion() + "\n" +
CONTENT_TYPE + ": " + request.headers().get(CONTENT_TYPE) + "\n" +
CONTENT_LENGTH + ": " + request.headers().get(CONTENT_LENGTH) + "\n";
this.logger.log(this.internalLevel,ctx.channel().toString() + " READ \n" + log);
}
ctx.fireChannelRead(msg);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) {
SessionContext sctx = serverContext.getSessionContextGroup().getSessionByChannel(ctx);
long now = Calendar.getInstance().getTimeInMillis();
long last = sctx.getLastRecvTime();
sctx.setLastRecvTime(now);
if ((now - last) < serverContext.getConfig().getColdDownMs()) {
serverContext.getSessionHandlerGroup().sendTooFastMsg(sctx);
}
sctx.setHeartCount(0);
try {
if (httpObject instanceof HttpRequest) {
httpRequest = (HttpRequest) httpObject;
if (!httpRequest.decoderResult().isSuccess()) {
return;
}
String uri = httpRequest.uri();
if (uri == null) {
return;
}
sctx.setSessionId(parseSessionId(httpRequest.headers().get(HttpHeaderNames.COOKIE)));
sctx.setRealAddress(ForwardedAddressUtil.parse(httpRequest.headers().get(ForwardedAddressUtil.KEY)));
HttpMethod method = httpRequest.method();
if (HttpMethod.GET.equals(method)) {
doGet(ctx, sctx);
} else if (HttpMethod.POST.equals(method)) {
postRequestDecoder = new HttpPostRequestDecoder(factory, httpRequest);
processHttpContent(ctx, sctx, (HttpContent) httpObject);
} else {
log.warn("not found request method[{}]", method.name());
}
} else if (httpObject instanceof HttpContent) {
processHttpContent(ctx, sctx, (HttpContent) httpObject);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
serverContext.getSessionHandlerGroup().unableParseMsg(sctx);
}
}
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest msg) throws UnsupportedEncodingException {
String uri = msg.uri();
QueryStringDecoder decoder = new QueryStringDecoder(uri);
logger.debug("Got Request for " + uri);
HttpResponseStatus status = fail ? HttpResponseStatus.BAD_REQUEST : HttpResponseStatus.OK;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
generator.writeStartObject();
for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
if (entry.getValue().size() == 1) {
generator.writeStringField(entry.getKey(), URLDecoder.decode(entry.getValue().get(0), "UTF-8"));
} else {
generator.writeArrayFieldStart(entry.getKey());
for (String value : entry.getValue()) {
generator.writeString(URLDecoder.decode(value, "UTF-8"));
}
generator.writeEndArray();
}
}
generator.writeEndObject();
generator.close();
} catch (Exception ex) {
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
ByteBuf byteBuf = Unpooled.wrappedBuffer(out.toByteArray());
responses.add(out.toString(StandardCharsets.UTF_8.name()));
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, byteBuf);
ChannelFuture future = ctx.channel().writeAndFlush(response);
future.addListener(ChannelFutureListener.CLOSE);
}
public URIDecoder(HttpRequest httpRequest, Map<String, String> extractedParams) {
super(httpRequest.uri());
this.paths = path().split("/");
if (httpRequest.method() == HttpMethod.PUT || httpRequest.method() == HttpMethod.POST) {
if (httpRequest instanceof HttpContent) {
this.contentType = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
if (contentType != null && contentType.equals(MediaType.APPLICATION_FORM_URLENCODED)) {
this.decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), httpRequest);
} else {
this.bodyData = ((HttpContent) httpRequest).content();
}
}
}
this.pathData = extractedParams;
}
public static String getUrl(HttpRequest request) {
String host = request.headers().get(HttpHeaderNames.HOST);
String url;
if (request.uri().indexOf("/") == 0) {
if (request.uri().length() > 1) {
url = host + request.uri();
} else {
url = host;
}
} else {
url = request.uri();
}
return url;
}
private String getEndpoint(HttpRequest request) {
String s = request.uri();
if (s.endsWith("/")) {
return s.substring(0, s.length() - 1);
}
return s;
}
public static ServerRequestImpl buildServerRequest(HttpRequest request, Observable<ByteBuffer> bodyStream) {
Charset messageCharset = HttpUtil.getCharset(request);
return new ServerRequestImpl(
request.method().name(),
buildHeadersMap(request.headers()),
request.uri(),
messageCharset,
new StreamedChunksBody(bodyStream, messageCharset));
}
@Override
protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Exception {
ByteBufUtil.copy(request.method().asciiName(), buf);
String uri = request.uri();
if (uri.isEmpty()) {
// Add " / " as absolute path if uri is not present.
// See http://tools.ietf.org/html/rfc2616#section-5.1.2
ByteBufUtil.writeMediumBE(buf, SPACE_SLASH_AND_SPACE_MEDIUM);
} else {
CharSequence uriCharSequence = uri;
boolean needSlash = false;
int start = uri.indexOf("://");
if (start != -1 && uri.charAt(0) != SLASH) {
start += 3;
// Correctly handle query params.
// See https://github.com/netty/netty/issues/2732
int index = uri.indexOf(QUESTION_MARK, start);
if (index == -1) {
if (uri.lastIndexOf(SLASH) < start) {
needSlash = true;
}
} else {
if (uri.lastIndexOf(SLASH, index) < start) {
uriCharSequence = new StringBuilder(uri).insert(index, SLASH);
}
}
}
buf.writeByte(SP).writeCharSequence(uriCharSequence, CharsetUtil.UTF_8);
if (needSlash) {
// write "/ " after uri
ByteBufUtil.writeShortBE(buf, SLASH_AND_SPACE_SHORT);
} else {
buf.writeByte(SP);
}
}
buf.writeCharSequence(request.protocolVersion().text(), CharsetUtil.US_ASCII);
ByteBufUtil.writeShortBE(buf, CRLF_SHORT);
}
private HttpRequestMessage buildZuulHttpRequest(
final HttpRequest nativeRequest, final ChannelHandlerContext clientCtx) {
// Setup the context for this request.
final SessionContext context;
if (decorator != null) { // Optionally decorate the context.
SessionContext tempContext = new SessionContext();
// Store the netty channel in SessionContext.
tempContext.set(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, clientCtx);
context = decorator.decorate(tempContext);
}
else {
context = new SessionContext();
}
// Get the client IP (ignore XFF headers at this point, as that can be app specific).
final Channel channel = clientCtx.channel();
final String clientIp = channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get();
// This is the only way I found to get the port of the request with netty...
final int port = channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get();
final String serverName = channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS).get();
final SocketAddress clientDestinationAddress = channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get();
// Store info about the SSL handshake if applicable, and choose the http scheme.
String scheme = SCHEME_HTTP;
final SslHandshakeInfo sslHandshakeInfo = channel.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get();
if (sslHandshakeInfo != null) {
context.set(CommonContextKeys.SSL_HANDSHAKE_INFO, sslHandshakeInfo);
scheme = SCHEME_HTTPS;
}
// Decide if this is HTTP/1 or HTTP/2.
String protocol = channel.attr(PROTOCOL_NAME).get();
if (protocol == null) {
protocol = nativeRequest.protocolVersion().text();
}
// Strip off the query from the path.
String path = nativeRequest.uri();
int queryIndex = path.indexOf('?');
if (queryIndex > -1) {
path = path.substring(0, queryIndex);
}
// Setup the req/resp message objects.
final HttpRequestMessage request = new HttpRequestMessageImpl(
context,
protocol,
nativeRequest.method().asciiName().toString().toLowerCase(),
path,
copyQueryParams(nativeRequest),
copyHeaders(nativeRequest),
clientIp,
scheme,
port,
serverName,
clientDestinationAddress,
false
);
// Try to decide if this request has a body or not based on the headers (as we won't yet have
// received any of the content).
// NOTE that we also later may override this if it is Chunked encoding, but we receive
// a LastHttpContent without any prior HttpContent's.
if (HttpUtils.hasChunkedTransferEncodingHeader(request) || HttpUtils.hasNonZeroContentLengthHeader(request)) {
request.setHasBody(true);
}
// Store this original request info for future reference (ie. for metrics and access logging purposes).
request.storeInboundRequest();
// Store the netty request for use later.
context.set(CommonContextKeys.NETTY_HTTP_REQUEST, nativeRequest);
// Store zuul request on netty channel for later use.
channel.attr(ATTR_ZUUL_REQ).set(request);
if (nativeRequest instanceof DefaultFullHttpRequest) {
final ByteBuf chunk = ((DefaultFullHttpRequest) nativeRequest).content();
request.bufferBodyContents(new DefaultLastHttpContent(chunk));
}
return request;
}