io.netty.handler.codec.http.HttpRequest # method ( ) 源码实例Demo

下面列出了 io.netty.handler.codec.http.HttpRequest # method ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest 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;
    }

    // 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);
    }
}
 
源代码2 项目: pdown-core   文件: HttpRequestInfo.java

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;
}
 
源代码3 项目: riposte   文件: RequestInfoImpl.java

public RequestInfoImpl(@NotNull HttpRequest request) {
    this(
        request.uri(),
        request.method(),
        request.headers(),
        HttpUtils.extractTrailingHeadersIfPossible(request),
        null,
        HttpUtils.extractCookies(request),
        null,
        HttpUtils.extractContentChunks(request),
        request.protocolVersion(),
        HttpUtil.isKeepAlive(request),
        (request instanceof FullHttpRequest),
        HttpPostRequestDecoder.isMultipart(request)
    );
}
 
源代码4 项目: nettice   文件: BaseAction.java

/**
 * 获取请求参数 Map
 */
private Map<String, List<String>> getParamMap(){
	Map<String, List<String>> paramMap = new HashMap<String, List<String>>();
	
	Object msg = DataHolder.getRequest();
	HttpRequest request = (HttpRequest) msg;
	HttpMethod method = request.method();
	if(method.equals(HttpMethod.GET)){
		String uri = request.uri();
		QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, Charset.forName(CharEncoding.UTF_8));
		paramMap = queryDecoder.parameters();
		
	}else if(method.equals(HttpMethod.POST)){
		FullHttpRequest fullRequest = (FullHttpRequest) msg;
		paramMap = getPostParamMap(fullRequest);
	}
	
	return paramMap;
}
 
源代码5 项目: blynk-server   文件: OTAHandler.java

@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;
}
 
源代码6 项目: socketio   文件: DisconnectHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof HttpRequest) {
    final HttpRequest req = (HttpRequest) msg;
    final HttpMethod requestMethod = req.method();
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
    final String requestPath = queryDecoder.path();

    boolean disconnect = queryDecoder.parameters().containsKey(DISCONNECT);
    if (disconnect) {
      if (log.isDebugEnabled())
        log.debug("Received HTTP disconnect request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      final String sessionId = PipelineUtils.getSessionId(requestPath);
      final Packet disconnectPacket = new Packet(PacketType.DISCONNECT, sessionId);
      disconnectPacket.setOrigin(PipelineUtils.getOrigin(req));
      ctx.fireChannelRead(disconnectPacket);
      ReferenceCountUtil.release(msg);
      return;
    }
  }
  ctx.fireChannelRead(msg);
}
 
源代码7 项目: crate   文件: HttpBlobHandler.java

private boolean possibleRedirect(HttpRequest request, String index, String digest) {
    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET) ||
        method.equals(HttpMethod.HEAD) ||
        (method.equals(HttpMethod.PUT) &&
         HttpUtil.is100ContinueExpected(request))) {
        String redirectAddress;
        try {
            redirectAddress = blobService.getRedirectAddress(index, digest);
        } catch (MissingHTTPEndpointException ex) {
            simpleResponse(request, HttpResponseStatus.BAD_GATEWAY);
            return true;
        }

        if (redirectAddress != null) {
            LOGGER.trace("redirectAddress: {}", redirectAddress);
            sendRedirect(request, activeScheme + redirectAddress);
            return true;
        }
    }
    return false;
}
 
源代码8 项目: crate   文件: HttpBlobHandler.java

private void handleBlobRequest(HttpRequest request, @Nullable HttpContent content) throws IOException {
    if (possibleRedirect(request, index, digest)) {
        return;
    }

    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET)) {
        get(request, index, digest);
        reset();
    } else if (method.equals(HttpMethod.HEAD)) {
        head(request, index, digest);
    } else if (method.equals(HttpMethod.PUT)) {
        put(request, content, index, digest);
    } else if (method.equals(HttpMethod.DELETE)) {
        delete(request, index, digest);
    } else {
        simpleResponse(request, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
}
 

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);
}
 
源代码10 项目: Summer   文件: WebRequestHandler.java

@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);
	}
}
 

@Nullable
@Override
public String getRequestHttpMethod(@Nullable HttpRequest request) {
    if (request == null) {
        return null;
    }

    HttpMethod method = request.method();
    if (method == null) {
        return null;
    }

    return method.name();
}
 
源代码12 项目: riposte   文件: StreamingAsyncHttpClient.java

protected @NotNull String getFallbackSpanName(@NotNull HttpRequest downstreamRequest) {
    try {
        HttpMethod method = downstreamRequest.method();
        String methodName = (method == null) ? null : method.name();
        return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest("async_downstream_call", methodName);
    }
    catch (Throwable t) {
        logger.error(
            "An unexpected error occurred while trying to extract fallback span name from Netty HttpRequest. "
            + "A hardcoded fallback name will be used as a last resort, however this error should be investigated "
            + "as it shouldn't be possible.", t
        );
        return "async_downstream_call-UNKNOWN_HTTP_METHOD";
    }
}
 

@NotNull String determineFallbackOverallRequestSpanName(@NotNull HttpRequest nettyRequest) {
    try {
        HttpMethod method = nettyRequest.method();
        String methodName = (method == null) ? null : method.name();
        return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(null, methodName);
    }
    catch (Throwable t) {
        logger.error(
            "An unexpected error occurred while trying to extract fallback span name from Netty HttpRequest. "
            + "A hardcoded fallback name will be used as a last resort, however this error should be investigated "
            + "as it shouldn't be possible.", t
        );
        return "UNKNOWN_HTTP_METHOD";
    }
}
 
源代码14 项目: blynk-server   文件: URIDecoder.java

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;
}
 
源代码15 项目: blynk-server   文件: BaseHttpHandler.java

private HandlerHolder lookupHandler(HttpRequest req) {
    for (HandlerWrapper handler : handlers) {
        if (handler.httpMethod == req.method()) {
            Matcher matcher = handler.uriTemplate.matcher(req.uri());
            if (matcher.matches()) {
                Map<String, String> extractedParams = handler.uriTemplate.extractParameters(matcher);
                return new HandlerHolder(handler, extractedParams);
            }
        }
    }
    return null;
}
 
源代码16 项目: socketio   文件: HandshakeHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  if (msg instanceof HttpRequest) {
    final HttpRequest req = (HttpRequest) msg;
    final HttpMethod requestMethod = req.method();
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
    final String requestPath = queryDecoder.path();

    if (!requestPath.startsWith(handshakePath)) {
      log.warn("Received HTTP bad request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
      ChannelFuture f = ctx.channel().writeAndFlush(res);
      f.addListener(ChannelFutureListener.CLOSE);
      ReferenceCountUtil.release(req);
      return;
    }

    if (HttpMethod.GET.equals(requestMethod) && requestPath.equals(handshakePath)) {
      if (log.isDebugEnabled())
        log.debug("Received HTTP handshake request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel());

      handshake(ctx, req, queryDecoder);
      ReferenceCountUtil.release(req);
      return;
    }
  }

  super.channelRead(ctx, msg);
}
 
源代码17 项目: blynk-server   文件: UploadHandler.java

public boolean accept(ChannelHandlerContext ctx, HttpRequest req) {
    return req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri);
}
 
源代码18 项目: ambry   文件: PublicAccessLogHandlerTest.java

/**
 * Sends the provided {@code httpRequest} and verifies that the response is as expected.
 * @param channel the {@link EmbeddedChannel} to send the request over.
 * @param httpRequest the {@link HttpRequest} that has to be sent
 * @param uri, Uri to be used for the request
 * @param headers {@link HttpHeaders} that is set in the request to be used for verification purposes
 * @param testErrorCase true if error case has to be tested, false otherwise
 * @param sslUsed true if SSL was used for this request.
 */
private void sendRequestCheckResponse(EmbeddedChannel channel, HttpRequest httpRequest, String uri,
    HttpHeaders headers, boolean testErrorCase, boolean chunkedResponse, boolean sslUsed) throws Exception {
  channel.writeInbound(httpRequest);
  if (uri.equals(EchoMethodHandler.DISCONNECT_URI)) {
    channel.disconnect();
  } else {
    channel.writeInbound(new DefaultLastHttpContent());
  }
  String lastLogEntry = publicAccessLogger.getLastPublicAccessLogEntry();
  // verify remote host, http method and uri
  String subString = testErrorCase ? "Error" : "Info" + ":embedded" + " " + httpRequest.method() + " " + uri;
  Assert.assertTrue("Public Access log entry doesn't have expected remote host/method/uri ",
      lastLogEntry.startsWith(subString));
  // verify SSL-related info
  subString = "SSL ([used=" + sslUsed + "]";
  if (sslUsed) {
    subString += ", [principal=" + PEER_CERT.getSubjectX500Principal() + "]";
    subString += ", [san=" + PEER_CERT.getSubjectAlternativeNames() + "]";
  }
  subString += ")";
  Assert.assertTrue("Public Access log entry doesn't have SSL info set correctly", lastLogEntry.contains(subString));
  // verify request headers
  verifyPublicAccessLogEntryForRequestHeaders(lastLogEntry, headers, httpRequest.method(), true);

  // verify response
  subString = "Response (";
  for (String responseHeader : RESPONSE_HEADERS.split(",")) {
    if (headers.contains(responseHeader)) {
      subString += "[" + responseHeader + "=" + headers.get(responseHeader) + "] ";
    }
  }
  subString += "[isChunked=" + chunkedResponse + "]), status=" + HttpResponseStatus.OK.code();

  if (!testErrorCase) {
    Assert.assertTrue("Public Access log entry doesn't have response set correctly",
        lastLogEntry.contains(subString));
  } else {
    Assert.assertTrue("Public Access log entry doesn't have error set correctly ",
        lastLogEntry.contains(": Channel closed while request in progress."));
  }
}
 
源代码19 项目: consulo   文件: HttpRequestUtil.java

public static boolean isWriteFromBrowserWithoutOrigin(HttpRequest request) {
  HttpMethod method = request.method();

  return StringUtil.isEmpty(getOrigin(request)) && isRegularBrowser(request) && (method == HttpMethod.POST || method == HttpMethod.PATCH || method == HttpMethod.PUT || method == HttpMethod.DELETE);
}