下面列出了 io.netty.handler.codec.http.FullHttpRequest # method ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public HttpRequestImpl(FullHttpRequest request) {
this.request = request;
this.parameters = new HashMap<>();
this.headers = request.headers();
this.multipartFiles = new ArrayList<>();
this.uriParser = new URIParser();
// 解析querystring上面的参数
queryStringDecoder = new QueryStringDecoder(request.uri());
uriParser.parse(queryStringDecoder.path());
parameters.putAll(queryStringDecoder.parameters());
in = new InputStreamImpl(request);
if (request.method() == HttpMethod.POST) {
parseHttpPostRequest(request);
}
}
private void parseHeader(FullHttpRequest httpRequest, SofaRequest sofaRequest) {
HttpHeaders headers = httpRequest.headers();
// 获取序列化类型
byte serializeType;
if (httpRequest.method() == HttpMethod.GET) {
serializeType = 0;
} else {
String codeName = headers.get(RemotingConstants.HEAD_SERIALIZE_TYPE);
if (codeName != null) {
serializeType = HttpTransportUtils.getSerializeTypeByName(codeName);
} else {
String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
serializeType = HttpTransportUtils.getSerializeTypeByContentType(contentType);
}
}
sofaRequest.setSerializeType(serializeType);
// 服务端应用
sofaRequest.setTargetAppName(headers.get(RemotingConstants.HEAD_TARGET_APP));
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
if (req.method() == HttpMethod.GET && req.uri().startsWith(connectPath)) {
final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
final String requestPath = queryDecoder.path();
if (log.isDebugEnabled())
log.debug("Received HTTP {} handshake request: {} from channel: {}", getTransportType().getName(), req, ctx.channel());
try {
handshake(ctx, req, requestPath);
} catch (Exception e) {
log.error("Error during {} handshake : {}", getTransportType().getName(), e);
} finally {
ReferenceCountUtil.release(msg);
}
return;
}
} else if (msg instanceof WebSocketFrame && isCurrentHandlerSession(ctx)) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
return;
}
ctx.fireChannelRead(msg);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
// Handle a bad request.
if (!req.decoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Send the index page
if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) {
String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
HttpUtil.setContentLength(res, content.readableBytes());
sendHttpResponse(ctx, req, res);
} else {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
}
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
FullHttpRequest request = (FullHttpRequest) msg;
HttpMethod method = request.method();
// if we are a post then we send upstream, otherwise we are just being prompted for a response.
if (method.equals(HttpMethod.POST)) {
ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content()));
// add a new response
responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)));
ReferenceCountUtil.release(msg);
return;
}
super.channelRead(ctx, msg);
}
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
// Allow only GET methods.
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
String supportedProtocolsCSV = StringUtil.joinStringList(supportedProtocols, ",");
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(this.getWebSocketLocation(req), supportedProtocolsCSV, false, maxFramePayloadLength);
this.httpRequest = req;
this.handshaker = wsFactory.newHandshaker(req);
if (this.handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req);
handshake.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
// we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toActiveMQBuffer and
// wrap it in a binary web socket frame before letting the wsencoder send it on the wire
WebSocketFrameEncoder encoder = new WebSocketFrameEncoder(maxFramePayloadLength);
future.channel().pipeline().addAfter("wsencoder", "websocket-frame-encoder", encoder);
} else {
// Handshake failed, fire an exceptionCaught event
future.channel().pipeline().fireExceptionCaught(future.cause());
}
}
});
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (FullHttpRequest.class.isAssignableFrom(msg.getClass())) {
FullHttpRequest req = FullHttpRequest.class.cast(msg);
DecoderResult result = req.decoderResult();
if (result.isFailure()) {
if (log.isWarnEnabled())
log.warn("http decoder failure", result.cause());
ReferenceCountUtil.release(msg);
ctx.writeAndFlush(HttpResponses.badRequest());
ctx.channel().close();
return;
}
if (HttpUtil.is100ContinueExpected(req))
ctx.writeAndFlush(new DefaultFullHttpResponse(req.protocolVersion(), CONTINUE));
FullHttpRequest safeReq = new DefaultFullHttpRequest(req.protocolVersion(),
req.method(),
req.uri(),
// Buffers.safeByteBuf(req.content(), ctx.alloc()),
req.content(),
req.headers(),
req.trailingHeaders());
channelRead(ctx, safeReq);
} else
ctx.fireChannelRead(msg);
}
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
String uri = msg.uri();
HttpMethod httpMethod = msg.method();
HttpHeaders headers = msg.headers();
if (HttpMethod.GET == httpMethod) {
String[] uriComponents = uri.split("[?]");
String endpoint = uriComponents[0];
String[] queryParams = uriComponents[1].split("&");
if ("/calculate".equalsIgnoreCase(endpoint)) {
String[] firstQueryParam = queryParams[0].split("=");
String[] secondQueryParam = queryParams[1].split("=");
Integer a = Integer.valueOf(firstQueryParam[1]);
Integer b = Integer.valueOf(secondQueryParam[1]);
String operator = headers.get("operator");
Operation operation = new Operation(a, b, operator);
ctx.fireChannelRead(operation);
}
} else {
throw new UnsupportedOperationException("HTTP method not supported");
}
}
@Override
protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final FullHttpRequest request) {
String requestPath = request.uri();
String requestBody = request.content().toString(CharsetUtil.UTF_8);
HttpMethod method = request.method();
if (!URL_PATTERN.matcher(requestPath).matches()) {
response(GSON.toJson(ResponseContentUtil.handleBadRequest("Not support request!")),
channelHandlerContext, HttpResponseStatus.BAD_REQUEST);
return;
}
if ("/scaling/job/start".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.POST)) {
startJob(channelHandlerContext, requestBody);
return;
}
if (requestPath.contains("/scaling/job/progress/") && method.equals(HttpMethod.GET)) {
getJobProgress(channelHandlerContext, requestPath);
return;
}
if ("/scaling/job/list".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.GET)) {
listAllJobs(channelHandlerContext);
return;
}
if ("/scaling/job/stop".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.POST)) {
stopJob(channelHandlerContext, requestBody);
return;
}
response(GSON.toJson(ResponseContentUtil.handleBadRequest("Not support request!")),
channelHandlerContext, HttpResponseStatus.BAD_REQUEST);
}
@Override
public boolean isSupported(FullHttpRequest request) {
return getMethod() == request.method() && myApiUrl.equals(request.uri());
}
private void serveContent(ChannelHandlerContext ctx, FullHttpRequest request) {
if (!request.decoderResult().isSuccess()) {
sendError(ctx, BAD_REQUEST);
return;
}
if (request.method() != HttpMethod.GET) {
return;
}
final String content = contentHolder.content;
if (content == null) {
log.error("No content for certificate.");
return;
}
log.info("Delivering content {}", content);
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
HttpUtil.setContentLength(response, content.length());
response.headers().set(CONTENT_TYPE, "text/html");
if (HttpUtil.isKeepAlive(request)) {
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
ctx.write(response);
// Write the content.
ChannelFuture lastContentFuture;
ByteBuf buf = ctx.alloc().buffer(content.length());
buf.writeBytes(content.getBytes());
ctx.write(buf);
lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
// Decide whether to close the connection or not.
if (!HttpUtil.isKeepAlive(request)) {
// Close the connection when the whole content is written out.
lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}
}
/** Used for conversion from {@link FullHttpRequest} to {@link HttpRequestMessage} */
public HttpRequestMessage(FullHttpRequest request) {
this(request.protocolVersion(), request.method(), request.uri(), request.content());
request.headers().forEach((entry) -> headers().set(entry.getKey(), entry.getValue()));
}
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
// Handle a bad request.
if (!req.decoderResult().isSuccess()) {
sendHttpResponse(ctx, req,
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.method() != HttpMethod.GET) {
sendHttpResponse(ctx, req,
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
return;
}
String uri = req.uri();
int index = uri.indexOf("?");
String paramterStr = "";
String path = null;
if (index == -1) {
path = uri;
} else {
path = uri.substring(0, index);
paramterStr = uri.substring(index+1);
}
if (websocketPath != null && websocketPath.trim().length() > 0 && websocketPath.equals(path)) {
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
WebSocketUtil.getWebSocketLocation(ctx.pipeline(), req, websocketPath), null, true, 5 * 1024 * 1024);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
if (!ctx.channel().hasAttr(WEBSOCKET_KEY)) {
Attribute<String> attr = ctx.channel().attr(WEBSOCKET_KEY);
attr.set("");
}
if (webSocketEvent != null) {
Map<String, Object> paramter = MapUrlParamsUtil.getUrlParams(paramterStr);
webSocketEvent.onOpenEvent(baseServer, new WebSocketSession(ctx.channel()), paramter);
}
}
} else {
if (httpResource != null) {
String resFileName = path;
ByteBuf res = httpResource.buildWebSocketRes(req, resFileName);
if (null == res) {
sendHttpResponse(ctx, req,
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
return;
} else {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
res));
}
}
return;
}
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
final FullHttpRequest req = (FullHttpRequest) msg;
if (isNotWebSocketPath(req)) {
ctx.fireChannelRead(msg);
return;
}
try {
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols,
allowExtensions, maxFramePayloadSize, allowMaskMismatch);
final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
// Kept for compatibility
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
ctx.fireUserEventTriggered(
new WebSocketServerProtocolHandler.HandshakeComplete(
req.uri(), req.headers(), handshaker.selectedSubprotocol()));
}
}
});
WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
ctx.pipeline().replace(this, "WS403Responder",
WebSocketServerProtocolHandler.forbiddenHttpRequestResponder());
}
} finally {
req.release();
}
}
private void doHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
if (request.decoderResult().isFailure()) {
ctx.close();
return;
}
// 握手使用get方法,所以我们控制只接受get方法
if (HttpMethod.GET != request.method()) {
ctx.close();
return;
}
String wsUrl = "ws://" + request.headers().get(HttpHeaderNames.HOST) + AKAXIN_WS_PATH;
WebSocketServerHandshakerFactory webSocketFactory = new WebSocketServerHandshakerFactory(wsUrl, null, true);
wsHandshaker = webSocketFactory.newHandshaker(request);
if (wsHandshaker != null) {
//
ChannelFuture channelFuture = wsHandshaker.handshake(ctx.channel(), request);
if (channelFuture.isSuccess()) {
// 握手并且验证用户webSessionId
QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri());
List<String> sessionIds = queryDecoder.parameters().get("sessionId");
if (sessionIds != null && sessionIds.size() > 0) {
String sessionId = sessionIds.get(0);
String siteUserId = WebSessionCache.getSiteUserId(sessionId);
// test siteUserId
siteUserId = "77151873-0fc7-4cf1-8bd6-67d00190fcf6";
if (StringUtils.isNotBlank(siteUserId)) {
ChannelSession channelSession = ctx.channel().attr(ChannelConst.CHANNELSESSION).get();
// siteUserId && sessionId 放入Channel缓存中
channelSession.setUserId(siteUserId);
WebChannelManager.addChannelSession(siteUserId, channelSession);
} else {
// cant get authed message ,so close the channel
// ctx.close();
}
} else {
ctx.close();
}
System.out.println("client handshaker success parm=" + queryDecoder.parameters());
}
} else {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
}
}
@Override
public boolean isSupported(@Nonnull FullHttpRequest request) {
return request.method() == HttpMethod.POST || request.method() == HttpMethod.OPTIONS;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(! (msg instanceof FullHttpRequest)){
result="未知请求!";
send(ctx,result,HttpResponseStatus.BAD_REQUEST);
return;
}
FullHttpRequest httpRequest = (FullHttpRequest)msg;
try{
String path=httpRequest.uri(); //获取路径
String body = getBody(httpRequest); //获取参数
HttpMethod method=httpRequest.method();//获取请求方法
//如果不是这个路径,就直接返回错误
if(!"/test".equalsIgnoreCase(path)){
result="非法请求!";
send(ctx,result,HttpResponseStatus.BAD_REQUEST);
return;
}
System.out.println("接收到:"+method+" 请求");
//如果是GET请求
if(HttpMethod.GET.equals(method)){
//接受到的消息,做业务逻辑处理...
System.out.println("body:"+body);
result="GET请求";
send(ctx,result,HttpResponseStatus.OK);
return;
}
//如果是POST请求
if(HttpMethod.POST.equals(method)){
//接受到的消息,做业务逻辑处理...
System.out.println("body:"+body);
result="POST请求";
send(ctx,result,HttpResponseStatus.OK);
return;
}
//如果是PUT请求
if(HttpMethod.PUT.equals(method)){
//接受到的消息,做业务逻辑处理...
System.out.println("body:"+body);
result="PUT请求";
send(ctx,result,HttpResponseStatus.OK);
return;
}
//如果是DELETE请求
if(HttpMethod.DELETE.equals(method)){
//接受到的消息,做业务逻辑处理...
System.out.println("body:"+body);
result="DELETE请求";
send(ctx,result,HttpResponseStatus.OK);
return;
}
}catch(Exception e){
System.out.println("处理请求失败!");
e.printStackTrace();
}finally{
//释放请求
httpRequest.release();
}
}
@Override
protected void handleRequest(
ChannelHandlerContext ctx,
FullHttpRequest req,
QueryStringDecoder decoder,
String[] segments)
throws ModelException {
if (isManagementReq(segments)) {
if (endpointMap.getOrDefault(segments[1], null) != null) {
handleCustomEndpoint(ctx, req, segments, decoder);
} else {
if (!"models".equals(segments[1])) {
throw new ResourceNotFoundException();
}
HttpMethod method = req.method();
if (segments.length < 3) {
if (HttpMethod.GET.equals(method)) {
handleListModels(ctx, decoder);
return;
} else if (HttpMethod.POST.equals(method)) {
handleRegisterModel(ctx, decoder, req);
return;
}
throw new MethodNotAllowedException();
}
if (HttpMethod.GET.equals(method)) {
handleDescribeModel(ctx, segments[2]);
} else if (HttpMethod.PUT.equals(method)) {
handleScaleModel(ctx, decoder, segments[2]);
} else if (HttpMethod.DELETE.equals(method)) {
handleUnregisterModel(ctx, segments[2]);
} else {
throw new MethodNotAllowedException();
}
}
} else {
chain.handleRequest(ctx, req, decoder, segments);
}
}
public static FullHttpResponse serveSite(Path siteDirectory,
FullHttpRequest request,
ByteBufAllocator alloc) throws IOException {
if (request.method() != HttpMethod.GET) {
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
}
String sitePath = request.uri();
while (sitePath.length() > 0 && sitePath.charAt(0) == '/') {
sitePath = sitePath.substring(1);
}
// we default to index.html, or what the plugin provides (as a unix-style path)
// this is a relative path under _site configured by the plugin.
if (sitePath.length() == 0) {
sitePath = "index.html";
}
final String separator = siteDirectory.getFileSystem().getSeparator();
// Convert file separators.
sitePath = sitePath.replace("/", separator);
Path file = siteDirectory.resolve(sitePath);
// return not found instead of forbidden to prevent malicious requests to find out if files exist or don't exist
if (!Files.exists(file) || FileSystemUtils.isHidden(file) ||
!file.toAbsolutePath().normalize().startsWith(siteDirectory.toAbsolutePath().normalize())) {
return Responses.contentResponse(
HttpResponseStatus.NOT_FOUND, alloc, "Requested file [" + file + "] was not found");
}
BasicFileAttributes attributes = readAttributes(file, BasicFileAttributes.class);
if (!attributes.isRegularFile()) {
// If it's not a regular file, we send a 403
final String msg = "Requested file [" + file + "] is not a valid file.";
return Responses.contentResponse(HttpResponseStatus.NOT_FOUND, alloc, msg);
}
try {
byte[] data = Files.readAllBytes(file);
var resp = Responses.contentResponse(HttpResponseStatus.OK, alloc, data);
resp.headers().set(HttpHeaderNames.CONTENT_TYPE, guessMimeType(file.toAbsolutePath().toString()));
return resp;
} catch (IOException e) {
return Responses.contentResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, alloc, e.getMessage());
}
}
public boolean isSupported(FullHttpRequest request) {
return request.method() == HttpMethod.GET || request.method() == HttpMethod.HEAD;
}