io.netty.handler.codec.http.DefaultFullHttpResponse Java Examples

The following examples show how to use io.netty.handler.codec.http.DefaultFullHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Http1ClientCodecUnitTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFullResponse() throws Exception {
  outputReceived = new CountDownLatch(1);
  ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "response");

  FullHttpResponse responseIn = new DefaultFullHttpResponse(HTTP_1_1, OK, body);

  channel.writeInbound(responseIn);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  Response responseOut = responses.remove(0);

  assertTrue(responseOut != null);
  assertTrue(responseOut instanceof FullResponse);
  assertEquals("HTTP/1.1", responseOut.version());
  assertEquals(OK, responseOut.status());
  assertTrue(responseOut.hasBody());
  assertFalse(responseOut.body() == null);
  assertEquals(body, responseOut.body());
}
 
Example #2
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new object to contain the response data
 *
 * @param streamId The stream associated with the response
 * @param http2Headers The initial set of HTTP/2 headers to create the response with
 * @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
 * @param validateHttpHeaders <ul>
 *        <li>{@code true} to validate HTTP headers in the http-codec</li>
 *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
 *        </ul>
 * @return A new response object which represents headers/data
 * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
 */
public static FullHttpResponse toFullHttpResponse(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc,
                                                  boolean validateHttpHeaders)
                throws Http2Exception {
    HttpResponseStatus status = parseStatus(http2Headers.status());
    // HTTP/2 does not define a way to carry the version or reason phrase that is included in an
    // HTTP/1.1 status line.
    FullHttpResponse msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, alloc.buffer(),
                                                       validateHttpHeaders);
    try {
        addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
    } catch (Http2Exception e) {
        msg.release();
        throw e;
    } catch (Throwable t) {
        msg.release();
        throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
    }
    return msg;
}
 
Example #3
Source File: FallbackResponder.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   counter.inc();
   byte[] content = null;

   try(InputStream is = FallbackResponder.class.getClassLoader().getResourceAsStream(resource)) {
      content = IOUtils.toByteArray(is);
   }

   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
   HttpHeaders.setContentLength(response, content.length);
   response.headers().set(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_XML_UTF_8.toString());
   response.content().writeBytes(content);
   ctx.write(response);
   ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
   future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #4
Source File: HttpHandlerUtil.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
public static FullHttpResponse buildJson(Object obj, Include include) {
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, AsciiString.cached("application/json; charset=utf-8"));
  if (obj != null) {
    try {
      ObjectMapper objectMapper = new ObjectMapper();
      if (include != null) {
        objectMapper.setSerializationInclusion(include);
      }
      String content = objectMapper.writeValueAsString(obj);
      response.content().writeBytes(content.getBytes(Charset.forName("utf-8")));
    } catch (JsonProcessingException e) {
      response.setStatus(HttpResponseStatus.SERVICE_UNAVAILABLE);
    }
  }
  response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
  return response;
}
 
Example #5
Source File: TrackerService.java    From twill with Apache License 2.0 6 votes vote down vote up
private void writeResourceReport(Channel channel) {
  ByteBuf content = Unpooled.buffer();
  Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8);
  try {
    reportAdapter.toJson(resourceReport.get(), writer);
    writer.close();
  } catch (IOException e) {
    LOG.error("error writing resource report", e);
    writeAndClose(channel, new DefaultFullHttpResponse(
      HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
      Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8)));
    return;
  }

  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
  HttpUtil.setContentLength(response, content.readableBytes());
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
  channel.writeAndFlush(response);
}
 
Example #6
Source File: NettyResponseUtil.java    From HAP-Java with MIT License 6 votes vote down vote up
public static FullHttpResponse createResponse(HttpResponse homekitResponse) {

    FullHttpResponse response =
        new DefaultFullHttpResponse(
            homekitResponse.getVersion() == HttpResponse.HttpVersion.EVENT_1_0
                ? EVENT_VERSION
                : HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(homekitResponse.getStatusCode()),
            Unpooled.copiedBuffer(homekitResponse.getBody()));
    for (Entry<String, String> header : homekitResponse.getHeaders().entrySet()) {
      response.headers().add(header.getKey(), header.getValue());
    }
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    return response;
  }
 
Example #7
Source File: ResponseEncoder.java    From ServerCore with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Response msg, List<Object> out) throws Exception {

    String content = msg.getContent();
    int byteBufLen = 0;
    if (content != null && content.length() > 0) {
        byteBufLen = content.length();
    }
    ByteBuf buf;
    if (byteBufLen > 0) {
        buf = ctx.alloc().buffer(byteBufLen);
        buf.writeBytes(content.getBytes());
    } else {
        buf = Unpooled.EMPTY_BUFFER;
    }

    DefaultFullHttpResponse httpResponse
            = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, msg.getStatus(), buf);
    httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, String.format("%s;charset=%s",msg.getContentType(),msg.getCharset()));
    httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().toString());
    if(msg.isKeepAlive()) {
        httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    out.add(httpResponse);
}
 
Example #8
Source File: Recipes.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a full HTTP response with the specified status, content type, and custom headers.
 *
 * <p>Headers should be specified as a map of strings. For example, to allow CORS, add the
 * following key and value: "access-control-allow-origin", "http://foo.example"
 *
 * <p>If content type or content length are passed in as custom headers, they will be ignored.
 * Instead, content type will be as specified by the parameter mediaTypes and content length will
 * be the length of the parameter contentLength.
 */
public static FullHttpResponse newResponse(
    HttpResponseStatus status,
    ByteBuf payload,
    ContentType contentType,
    Map<String, String> customHeaders) {
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, payload);

  if (customHeaders != null) {
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
      response.headers().set(entry.getKey(), entry.getValue());
    }
  }

  response.headers().set(CONTENT_TYPE, contentType.value);
  response.headers().setInt(CONTENT_LENGTH, payload.readableBytes());

  return response;
}
 
Example #9
Source File: HttpChannelImpl.java    From InChat with Apache License 2.0 6 votes vote down vote up
@Override
public void getState(Channel channel, SendServerVO serverVO) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpConstant.CONTENT_TYPE, HttpConstant.APPLICATION_JSON);
    if (serverVO.getToken() == "") {
        notFindUri(channel);
    }
    Boolean state = WebSocketCacheMap.hasToken(serverVO.getToken());
    StateVo stateVo = new StateVo(serverVO.getToken(), state);
    ResultVO<StateVo> resultVO = new ResultVO<>(HttpResponseStatus.OK.code(), stateVo);
    Gson gson = new Gson();
    ByteBuf buf = Unpooled.copiedBuffer(gson.toJson(resultVO), CharsetUtil.UTF_8);
    response.content().writeBytes(buf);
    channel.writeAndFlush(response);
    close(channel);
}
 
Example #10
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void sendDecodingFailures(ChannelHandlerContext ctx, Throwable t, Object msg) {
	Throwable cause = t.getCause() != null ? t.getCause() : t;

	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Decoding failed: " + msg + " : "), cause);
	}

	ReferenceCountUtil.release(msg);

	HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
			cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE:
			                                         HttpResponseStatus.BAD_REQUEST);
	response.headers()
	        .setInt(HttpHeaderNames.CONTENT_LENGTH, 0)
	        .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
	ctx.writeAndFlush(response)
	   .addListener(ChannelFutureListener.CLOSE);
}
 
Example #11
Source File: NonSslRedirectHandler.java    From qonduit with Apache License 2.0 6 votes vote down vote up
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(HttpHeaderNames.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
Example #12
Source File: SpdyServerHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = isKeepAlive(req);

        ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example #13
Source File: HttpSuggestRequestHandler.java    From timely with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, SuggestRequest msg) throws Exception {
    byte[] buf = null;
    try {
        buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.suggest(msg));
    } catch (TimelyException e) {
        LOG.error(e.getMessage(), e);
        this.sendHttpError(ctx, e);
        return;
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
 
Example #14
Source File: HelloWorldHttp1Handler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #15
Source File: WebSocketServerHandler.java    From withme3.0 with MIT License 6 votes vote down vote up
/**
 * 给客户端回复消息
 *
 * @param ctx
 * @param req
 * @param res
 */
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {

    //返回应答给客户端
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
    }

    // 如果是非Keep-Alive,关闭连接
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #16
Source File: Http1ServerChannelHandler.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected int sendHttp1Response(ChannelHandlerContext ctx, HttpResponseStatus status, String resultStr,
                                boolean isKeepAlive) {
    ByteBuf content = Unpooled.copiedBuffer(resultStr, RpcConstants.DEFAULT_CHARSET);
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    res.headers().set(CONTENT_TYPE, "text/html; charset=" + RpcConstants.DEFAULT_CHARSET.displayName());
    HttpUtil.setContentLength(res, content.readableBytes());
    try {
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (isKeepAlive) {
            HttpUtil.setKeepAlive(res, true);
        } else {
            HttpUtil.setKeepAlive(res, false); //set keepalive closed
            f.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e2) {
        LOGGER.warn("Failed to send HTTP response to remote, cause by:", e2);
    }

    return content.readableBytes();
}
 
Example #17
Source File: NettyUtils.java    From gae with MIT License 6 votes vote down vote up
public static FullHttpResponse buildResponse(BidResponse bidResponse) {
    String respJson = JSON.toJSONString(bidResponse, jsonSnakeConfig);
    // byte[] buf = JSON.toJSONBytes(bidResponse, jsonSnakeConfig);

    FullHttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(respJson.getBytes())
    );

    response.headers().set(
            HttpHeaderNames.CONTENT_TYPE.toString(),
            "application/json;charset=utf8"
    );

    log.info("gae_response\t{}", respJson);

    return response;
}
 
Example #18
Source File: HelloWorldHandler.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) {
  if (!(msg instanceof HttpRequest)) return;
  HttpRequest req = (HttpRequest) msg;

  if (HttpUtil.is100ContinueExpected(req)) {
    ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
  }
  boolean keepAlive = HttpUtil.isKeepAlive(req);
  FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
    Unpooled.wrappedBuffer(HELLO_WORLD));
  response.headers().set(CONTENT_TYPE, "text/plain");
  response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

  if (!keepAlive) {
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  } else {
    response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    ctx.write(response);
  }
}
 
Example #19
Source File: WebSocketServerHandshaker08.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Handle the web socket handshake for the web socket specification <a href=
 * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08">HyBi version 8 to 10</a>. Version 8, 9 and
 * 10 share the same wire protocol.
 * </p>
 *
 * <p>
 * Browser request to the server:
 * </p>
 *
 * <pre>
 * GET /chat HTTP/1.1
 * Host: server.example.com
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Protocol: chat, superchat
 * Sec-WebSocket-Version: 8
 * </pre>
 *
 * <p>
 * Server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 */
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);

    if (headers != null) {
        res.headers().add(headers);
    }

    CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
    if (key == null) {
        throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    }
    String acceptSeed = key + WEBSOCKET_08_ACCEPT_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    String accept = WebSocketUtil.base64(sha1);

    if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 08 server handshake key: {}, response: {}", key, accept);
    }

    res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
    res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);

    String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    if (subprotocols != null) {
        String selectedSubprotocol = selectSubprotocol(subprotocols);
        if (selectedSubprotocol == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
            }
        } else {
            res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
        }
    }
    return res;
}
 
Example #20
Source File: HttpSender.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public void sendRedirect(ChannelHandlerContext ctx, String newUri, FullHttpRequest req) {
   FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
   response.headers().set(LOCATION, newUri);
   metrics.incHTTPResponseCounter(className, HttpSender.STATUS_FOUND);
   // Close the connection as soon as the redirect message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #21
Source File: HttpStaticFileServerHandler.java    From timely with Apache License 2.0 5 votes vote down vote up
private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
    response.headers().set(LOCATION, newUri);

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
}
 
Example #22
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static FullHttpResponse theHttpContent(String str, String contentType) {
	ByteBuf byteBuf = Unpooled.copiedBuffer(str.getBytes());	
	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK ,byteBuf);
	response.headers().set(CONTENT_TYPE, contentType);
	response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
	response.headers().set(CONNECTION, HEADER_CONNECTION_CLOSE);		
	return response;
}
 
Example #23
Source File: ServletContentHandler.java    From Jinx with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (request != null) {
        //X-Real-IP
        Optional<String> option = Optional.ofNullable(request.headers().get("X-Forwarded-For"));
        String real = option.orElseGet(() -> request.headers().get("X-Real-IP"));
        //X-Forwarded-For
        if (StringUtils.isBlank(real)) {
            InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
            real = socketAddr.getAddress().getHostAddress();
        }
        /**
         * 如果发送生错误
         */
        if (!request.decoderResult().isSuccess()) {
            sendError(ctx, HttpResponseStatus.BAD_GATEWAY);
            return;
        }

        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false);
        NettyHttpServletResponse servletResponse
                = new NettyHttpServletResponse(ctx, servletContext, response);
        NettyHttpServletRequest servletRequest
                = new NettyHttpServletRequest(ctx, servletContext, request,
                servletResponse, inputStream);
        if (HttpHeaders.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE),
                    ctx.voidPromise());
        }
        ctx.fireChannelRead(servletRequest);
    }
    if (request != null) {
        inputStream.addContent(request);
    }
}
 
Example #24
Source File: WebSocketServerHandshaker13.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Handle the web socket handshake for the web socket specification <a href=
 * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">HyBi versions 13-17</a>. Versions 13-17
 * share the same wire protocol.
 * </p>
 *
 * <p>
 * Browser request to the server:
 * </p>
 *
 * <pre>
 * GET /chat HTTP/1.1
 * Host: server.example.com
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Protocol: chat, superchat
 * Sec-WebSocket-Version: 13
 * </pre>
 *
 * <p>
 * Server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 */
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
    if (headers != null) {
        res.headers().add(headers);
    }

    CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
    if (key == null) {
        throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    }
    String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    String accept = WebSocketUtil.base64(sha1);

    if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept);
    }

    res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
    res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);

    String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    if (subprotocols != null) {
        String selectedSubprotocol = selectSubprotocol(subprotocols);
        if (selectedSubprotocol == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
            }
        } else {
            res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
        }
    }
    return res;
}
 
Example #25
Source File: HttpClientOperationsTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void doTestStatus(HttpResponseStatus status) {
	EmbeddedChannel channel = new EmbeddedChannel();
	HttpClientOperations ops = new HttpClientOperations(() -> channel,
			ConnectionObserver.emptyListener(),
			ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT);
	ops.setNettyResponse(new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.EMPTY_BUFFER));
	assertEquals(status.reasonPhrase(), ops.status().reasonPhrase());
}
 
Example #26
Source File: Handlers.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
static void sendError(final ChannelHandlerContext ctx, final HttpResponseStatus status) {
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().set("X-Talend-Proxy-JUnit", "default-response");
    ctx.writeAndFlush(response);
}
 
Example #27
Source File: RestHandler.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx) {
	DefaultFullHttpResponse response = 
			new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
	HttpServerHandler.sendHttpMessage(response, ctx.channel()).
							addListener(ChannelFutureListener.CLOSE).
							addListener(new FilnalEventListener(ctx, true));
}
 
Example #28
Source File: HttpResponses.java    From cantor with Apache License 2.0 5 votes vote down vote up
private static FullHttpResponse error(HandlerRequest request, HttpResponseStatus status) {
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.valueOf(request.version()),
                                                        status);
    String content = status.toString();
    resp.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), content.length());
    ByteBufUtil.writeUtf8(resp.content(), content);
    return resp;
}
 
Example #29
Source File: ResponseSender.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected HttpResponse createActualResponseObjectForFirstChunk(
    ResponseInfo<?> responseInfo,
    RequestInfo<?> requestInfo,
    ObjectMapper serializer,
    ChannelHandlerContext ctx
) {
    HttpResponseStatus httpStatus =
        HttpResponseStatus.valueOf(responseInfo.getHttpStatusCodeWithDefault(DEFAULT_HTTP_STATUS_CODE));

    if (responseInfo.isChunkedResponse()) {
        // Chunked response. No content (yet). Return a DefaultHttpResponse (not a full one) for the first chunk
        //      of a chunked response.
        return new DefaultHttpResponse(HTTP_1_1, httpStatus);
    }
    else {
        // Full response. There may or may not be content.
        Object content = responseInfo.getContentForFullResponse();
        if (content == null || isContentAlwaysEmpty(requestInfo, responseInfo)) {
            // No content, or this is a response status code that MUST NOT send a payload, so return a simple full
            //      response without a payload.
            return new DefaultFullHttpResponse(HTTP_1_1, httpStatus);
        }
        else {
            // There is content and this is not a response that prohibits a payload. Serialize the content to a
            //      ByteBuf for the response.
            ByteBuf bytesForResponse = serializeOutputToByteBufForResponse(
                responseInfo.getContentForFullResponse(), responseInfo, serializer, ctx
            );
            // Return a full response with the serialized payload.
            return new DefaultFullHttpResponse(HTTP_1_1, httpStatus, bytesForResponse);
        }
    }
}
 
Example #30
Source File: HttpStaticFileServerHandler.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}