下面列出了 io.netty.handler.codec.http.HttpRequest # getMethod ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void handle(ChannelHandlerContext ctx, HttpRequest req)
throws IOException, URISyntaxException {
String op = params.op();
HttpMethod method = req.getMethod();
if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op)
&& method == PUT) {
onCreate(ctx);
} else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op)
&& method == POST) {
onAppend(ctx);
} else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op)
&& method == GET) {
onOpen(ctx);
} else if(GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op)
&& method == GET) {
onGetFileChecksum(ctx);
} else {
throw new IllegalArgumentException("Invalid operation " + op);
}
}
public void handle(ChannelHandlerContext ctx, HttpRequest req)
throws IOException, URISyntaxException {
String op = params.op();
HttpMethod method = req.getMethod();
if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op)
&& method == PUT) {
onCreate(ctx);
} else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op)
&& method == POST) {
onAppend(ctx);
} else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op)
&& method == GET) {
onOpen(ctx);
} else if(GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op)
&& method == GET) {
onGetFileChecksum(ctx);
} else {
throw new IllegalArgumentException("Invalid operation " + op);
}
}
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req)
throws Exception {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
/**
* 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;
}
}
/**
*
* @param factory
* the factory used to create InterfaceHttpData
* @param request
* the request to encode
* @param multipart
* True if the FORM is a ENCTYPE="multipart/form-data"
* @param charset
* the charset to use as default
* @param encoderMode
* the mode for the encoder to use. See {@link EncoderMode} for the details.
* @throws NullPointerException
* for request or charset or factory
* @throws ErrorDataEncoderException
* if the request is not a POST
*/
public HttpPostRequestEncoder(
HttpDataFactory factory, HttpRequest request, boolean multipart, Charset charset,
EncoderMode encoderMode)
throws ErrorDataEncoderException {
if (factory == null) {
throw new NullPointerException("factory");
}
if (request == null) {
throw new NullPointerException("request");
}
if (charset == null) {
throw new NullPointerException("charset");
}
if (request.getMethod() != HttpMethod.POST) {
throw new ErrorDataEncoderException("Cannot create a Encoder if not a POST");
}
this.request = request;
this.charset = charset;
this.factory = factory;
// Fill default values
bodyListDatas = new ArrayList<InterfaceHttpData>();
// default mode
isLastChunk = false;
isLastChunkSent = false;
isMultipart = multipart;
multipartHttpDatas = new ArrayList<InterfaceHttpData>();
this.encoderMode = encoderMode;
if (isMultipart) {
initDataMultipart();
}
}
@Override
public void handle(RakamHttpRequest request) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(request), null, true);
handshaker = wsFactory.newHandshaker(request.getRequest());
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(request.context().channel());
} else {
HttpRequest request1 = request.getRequest();
DefaultFullHttpRequest defaultFullHttpRequest = new DefaultFullHttpRequest(request1.getProtocolVersion(), request1.getMethod(), request1.getUri());
defaultFullHttpRequest.headers().set(request1.headers());
handshaker.handshake(request.context().channel(), defaultFullHttpRequest);
onOpen(new WebSocketRequest(request));
}
}
public void track(HttpRequest request) {
// check if tenantId is being tracked by JMX TenantTrackerMBean and log the request if it is
if (request == null) return;
String tenantId = findTid( request.getUri() );
if (isTracking(tenantId)) {
// get headers
String headers = EMPTY_STRING;
for (String headerName : request.headers().names()) {
headers += "\n" + headerName + "\t" + request.headers().get(headerName);
}
// get parameters
String queryParams = getQueryParameters(request);
// get request content
String requestContent = EMPTY_STRING;
if ( request instanceof FullHttpRequest ) {
FullHttpRequest fullReq = (FullHttpRequest)request;
requestContent = fullReq.content().toString(Constants.DEFAULT_CHARSET);
if ((requestContent != null) && (!requestContent.isEmpty())) {
requestContent = "\nREQUEST_CONTENT:\n" + requestContent;
}
}
// log request
String logMessage = "[TRACKER] " +
request.getMethod() + " request for tenantId " + tenantId + ": " + request.getUri() + queryParams + "\n" +
"HEADERS: " + headers +
requestContent;
if (doesMessageContainMetricNames(logMessage)) {
log.info(logMessage);
}
}
}
public void trackResponse(HttpRequest request, FullHttpResponse response) {
// check if tenantId is being tracked by JMX TenantTrackerMBean and log the response if it is
// HttpRequest is needed for original request uri and tenantId
if (request == null) return;
if (response == null) return;
String tenantId = findTid( request.getUri() );
if (isTracking(tenantId)) {
HttpResponseStatus status = response.getStatus();
String messageBody = response.content().toString(Constants.DEFAULT_CHARSET);
// get parameters
String queryParams = getQueryParameters(request);
// get headers
String headers = "";
for (String headerName : response.headers().names()) {
headers += "\n" + headerName + "\t" + response.headers().get(headerName);
}
// get response content
String responseContent = "";
if ((messageBody != null) && (!messageBody.isEmpty())) {
responseContent = "\nRESPONSE_CONTENT:\n" + messageBody;
}
String logMessage = "[TRACKER] " +
"Response for tenantId " + tenantId + " " + request.getMethod() + " request " + request.getUri() + queryParams +
"\nRESPONSE_STATUS: " + status.code() +
"\nRESPONSE HEADERS: " + headers +
responseContent;
log.info(logMessage);
}
}
/**
* request regular expression
*/
// public final static Pattern Req_Regx = Pattern
// .compile("\\/(.*?)\\/(.*?)(?:\\/(.*))?");
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
if (LOG.isDebugEnabled()) {
LOG.debug("Dispatch req path {} method {}", req.getUri(), req.getMethod().name());
}
// pay client req
final String reqUrl = req.getUri();
Map<String, WeakReference<String>> cache = _cache;
WeakReference<String> wr = cache.get(reqUrl);
String clazz = wr != null && wr.get() != null ? wr.get() : null;
if (clazz != null) {
// if (reqUrl.startsWith("/common/image/download")) {
// ctx.pipeline().addLast("http aggregator",
// new HttpObjectAggregator(65536));
// ctx.pipeline().addLast("http chunk",
// new ChunkedWriteHandler());
// }
ctx.pipeline().addLast((ChannelHandler) getClass().getClassLoader().loadClass(clazz).newInstance());
} else {
List<Dispatcher> list = _dispatcher;
boolean notFound = true;
for (Dispatcher d : list) {
if (d.getMethod().contains(req.getMethod().name()) && Pattern.matches(d.getUrl(), reqUrl)) {
// if (d.getId().equals("img.down")) {
// ctx.pipeline().remove("http compressor");
// ctx.pipeline().addLast("http aggregator",
// new HttpObjectAggregator(65536)); //
// ctx.pipeline().addLast("http chunk",
// new ChunkedWriteHandler());
// }
ctx.pipeline().addLast(
(ChannelHandler) getClass().getClassLoader().loadClass(d.getClazz()).newInstance());
cache.put(reqUrl, new WeakReference<String>(d.getClazz()));
notFound = false;
break;
}
}
if (notFound) {
// ctx.pipeline().addLast(VoidHandler);
// cache.put(reqUrl, new
// WeakReference<String>(VoidHandler.getClass().getName()));
// LOG.error("Not found reqUrl->{}", reqUrl);
throw new Exception("HttpReqDispatcher not match uri->" + reqUrl + " method->" + req.getMethod());
}
}
}
ReferenceCountUtil.retain(msg);
ctx.fireChannelRead(msg);
}
public void requestReceivedFromClient(FlowContext flowContext,
HttpRequest httpRequest) {
if (httpRequest.getMethod() != HttpMethod.CONNECT) {
count.incrementAndGet();
}
}
public void requestReceivedFromClient(FlowContext flowContext,
HttpRequest httpRequest) {
if (httpRequest.getMethod() != HttpMethod.CONNECT) {
count.incrementAndGet();
}
}
/**
* Returns true if the specified request is a request to an origin server, rather than to a proxy server. If this
* request is being MITM'd, this method always returns false. The format of requests to a proxy server are defined
* in RFC 7230, section 5.3.2 (all other requests are considered requests to an origin server):
<pre>
When making a request to a proxy, other than a CONNECT or server-wide
OPTIONS request (as detailed below), a client MUST send the target
URI in absolute-form as the request-target.
[...]
An example absolute-form of request-line would be:
GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1
To allow for transition to the absolute-form for all requests in some
future version of HTTP, a server MUST accept the absolute-form in
requests, even though HTTP/1.1 clients will only send them in
requests to proxies.
</pre>
*
* @param httpRequest the request to evaluate
* @return true if the specified request is a request to an origin server, otherwise false
*/
private boolean isRequestToOriginServer(HttpRequest httpRequest) {
// while MITMing, all HTTPS requests are requests to the origin server, since the client does not know
// the request is being MITM'd by the proxy
if (httpRequest.getMethod() == HttpMethod.CONNECT || isMitming()) {
return false;
}
// direct requests to the proxy have the path only without a scheme
String uri = httpRequest.getUri();
return !HTTP_SCHEME.matcher(uri).matches();
}