@Override public void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception { if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); ByteBuf content = ctx.alloc().buffer(); content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate()); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.writeAndFlush(response); } }
@SuppressWarnings("unused") @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { FullHttpRequest request = (FullHttpRequest) msg; try { Response httpResp = invoke(parse(request)); DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResp.getStatus().getStatus(), httpResp.buffer()); if (httpResp != null) { HttpHeaderUtil.setContentLength(response, response.content().readableBytes()); HttpHeaderUtil.setKeepAlive(response, true); ctx.channel().writeAndFlush(response); } else { ctx.writeAndFlush( new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, httpResp.buffer())); } } finally { request.content().release(); } }
private boolean directHandleMethod(ChannelHandlerContext ctx, FullHttpRequest request, HttpMethod method) { if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.POST)) { return false; } // 处理 OPTIONS 请求 HttpResponseStatus status = HttpResponseStatus.OK; boolean invalid = false; if (!method.equals(HttpMethod.OPTIONS)) { invalid = true; status = HttpResponseStatus.METHOD_NOT_ALLOWED; } DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.EMPTY_BUFFER); HttpHeaders headers = response.headers(); // headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, // "X-Requested-With, accept, origin, content-type"); headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "X-Requested-With, content-type"); headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS"); headers.set(HttpHeaderNames.SERVER, "Netty5"); if (invalid) { headers.set("Client-Warning", "Invalid Method"); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(request); if (keepAlive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } return true; }
protected void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaderUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
@Override protected void decode(ChannelHandlerContext ctx, FullHttpRequest request, List<Object> out) throws Exception { // Handle a bad request. if (!request.decoderResult().isSuccess()) { sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } if ("websocket".equalsIgnoreCase((String) request.headers().get("Upgrade"))) { handleWebSocket(ctx, request); return; } String queryStr = request.uri(); if ("/favicon.ico".equals(queryStr)) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, request, res); return; } if (queryStr != null) { queryStr = queryStr.trim(); if (queryStr.length() > 0 && queryStr.charAt(0) == '/') { if (queryStr.length() == 1) { queryStr = ""; } else { int wh = queryStr.indexOf('?'); if (wh > 0) { queryStr = queryStr.substring(wh + 1); } else { queryStr = queryStr.substring(1); } } } } else { queryStr = ""; } HttpMethod method = request.method(); logger.debug("decode queryStr ={}, method={}, msg={}", queryStr, method, request); if (directHandleMethod(ctx, request, method)) { return; } ByteBuf content; if (queryStr.length() == 0) { if (HttpMethod.GET.equals(method)) { handleHttpHomePage(ctx, request); return; } content = request.content().retain(); } else { queryStr = URLDecoder.decode(queryStr, "UTF-8"); int strLen = queryStr.length(); if (queryStr.charAt(0) != '[' && strLen > 5) { boolean wordOrLetter = Character.isLetterOrDigit(queryStr.charAt(strLen - 1)); for (int i = 2, MAX = Math.min(strLen, 7); i < MAX; i++) { char c = queryStr.charAt(strLen - i); if (c == '.') { if (wordOrLetter) { serverDef.httpResourceHandler.process(ctx, request, queryStr, strLen - i); return; } break; } else if (wordOrLetter && !Character.isLetterOrDigit(c)) { wordOrLetter = false; } } } byte[] bytes = queryStr.getBytes(); // System.err.println("URI: bytes[0] = "+bytes[0]+", len = // "+bytes.length); content = ctx.alloc().buffer(bytes.length); content.writeBytes(bytes); } logger.debug("content.size = " + content.readableBytes()); out.add(content); boolean alive = HttpHeaderUtil.isKeepAlive(request); Object event = alive ? thriftMessageWrapperKeepAlive : thriftMessageWrapperNormal; ctx.fireUserEventTriggered(event); }