當前位置: 首頁>>代碼示例>>Java>>正文


Java DefaultFullHttpResponse類代碼示例

本文整理匯總了Java中io.netty.handler.codec.http.DefaultFullHttpResponse的典型用法代碼示例。如果您正苦於以下問題:Java DefaultFullHttpResponse類的具體用法?Java DefaultFullHttpResponse怎麽用?Java DefaultFullHttpResponse使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DefaultFullHttpResponse類屬於io.netty.handler.codec.http包,在下文中一共展示了DefaultFullHttpResponse類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: writeBack

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
    ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
    HttpResponseStatus status;
    if (isSuccess) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    //logger.info("result str:{}", resultStr);
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, content.readableBytes());
    try {
        ChannelFuture f = channel.writeAndFlush(res);
        if (isKeepAlive) {
            HttpHeaders.setKeepAlive(res, true);
        } else {
            HttpHeaders.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();
}
 
開發者ID:tiglabs,項目名稱:jsf-sdk,代碼行數:27,代碼來源:HttpJsonHandler.java

示例2: handleHttpRequest

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
/**
 * 接受http信息
 * @param ctx
 * @param req
 */
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            getWebSocketLocation(req), null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}
 
開發者ID:ninelook,項目名稱:wecard-server,代碼行數:23,代碼來源:NettyServerHandler.java

示例3: writeResponse

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
        HTTP_1_1, currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST,
        Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
開發者ID:aerogear,項目名稱:push-network-proxies,代碼行數:25,代碼來源:MockingFCMServerHandler.java

示例4: get

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Override
public FullHttpResponse get(ChannelHandlerContext channelHandlerContext, QueryDecoder queryDecoder, PathProvider path, HttpRequest httpRequest) throws Exception
{
    CloudNet.getLogger().debug("HTTP Request from " + channelHandlerContext.channel().remoteAddress());

    StringBuilder stringBuilder = new StringBuilder();

    try (InputStream inputStream = WebsiteDocumentation.class.getClassLoader().getResourceAsStream("files/api-doc.txt");
         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)))
    {
        String input;
        while ((input = bufferedReader.readLine()) != null)
        {
            stringBuilder.append(input).append(System.lineSeparator());
        }
    }

    String output = stringBuilder.substring(0);
    ByteBuf byteBuf = Unpooled.wrappedBuffer(output.getBytes(StandardCharsets.UTF_8));
    FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK, byteBuf);
    fullHttpResponse.headers().set("Content-Type", "text/plain");
    return fullHttpResponse;
}
 
開發者ID:Dytanic,項目名稱:CloudNet,代碼行數:24,代碼來源:WebsiteDocumentation.java

示例5: newResponse

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
/**
 * 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 contentType 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;
}
 
開發者ID:Nordstrom,項目名稱:xrpc,代碼行數:29,代碼來源:Recipes.java

示例6: shouldHandlerRequestAndResponse

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Test
public void shouldHandlerRequestAndResponse() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    inboundChannel.write(req);

    assertEquals(1, inboundChannel.outboundMessages().size());

    Object outboundReq = inboundChannel.outboundMessages().poll();
    assertTrue(outboundReq instanceof ByteBuf);
    assertEquals("GET / HTTP/1.1\r\n\r\n", new String(readBytes((ByteBuf) outboundReq)));

    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    assertFalse(inboundChannel.writeInbound(resp));

    assertEquals(1, outboundChannel.outboundMessages().size());
    assertEquals(resp, outboundChannel.outboundMessages().poll());

    resp.release();
}
 
開發者ID:chhsiao90,項目名稱:nitmproxy,代碼行數:24,代碼來源:Http1BackendHandlerTest.java

示例7: channelRead0

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req)
		throws Exception {
	if (!req.getDecoderResult().isSuccess()) {
		logger.debug("invalid http request");
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				BAD_REQUEST));
		return;
	}

	if (req.getUri().equalsIgnoreCase(this.websocketUri)) {
		logger.debug("it is websocket request");
		ctx.fireChannelRead(req.retain());
		return;
	}

	HttpTransport transport = getTransport(req);
	if (transport == null) {
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				BAD_REQUEST));
	} else {
		transport.handleRequest(ctx, req);
	}
}
 
開發者ID:osswangxining,項目名稱:mqttserver,代碼行數:25,代碼來源:HttpRequestHandler.java

示例8: handleRequest

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Override
public void handleRequest(ChannelHandlerContext ctx, FullHttpRequest req)
		throws Exception {
	if (req.getUri().contains("/jsonp/connect")) {
		handleConnect(ctx, req);
	} else if (req.getUri().contains("/jsonp/subscribe")) {
		handleSubscrible(ctx, req);
	} else if (req.getUri().contains("/jsonp/waiting")) {
		handleWaitingMsg(ctx, req);
	} else if (req.getUri().contains("/jsonp/unsubscrible")) {
		handleUnsubscrible(ctx, req);
	} else if (req.getUri().contains("/jsonp/publish")) {
		handlePublish(ctx, req);
	} else if (req.getUri().contains("/jsonp/disconnect")) {
		handleDisconnect(ctx, req);
	} else { // invalid request
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				BAD_REQUEST));
	}
}
 
開發者ID:osswangxining,項目名稱:mqttserver,代碼行數:21,代碼來源:HttpJsonpTransport.java

示例9: handleUnsubscrible

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
private void handleUnsubscrible(ChannelHandlerContext ctx, HttpRequest req) {
	if (!HttpSessionStore.checkJSessionId(req)) {
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				UNAUTHORIZED));
		return;
	}

	String topic = HttpSessionStore.getParameter(req, "topic");
	String sessionId = HttpSessionStore.getClientSessionId(req);

	HttpChannelEntity httpChannelEntity = (HttpChannelEntity) MemoryMetaPool
			.getChannelEntryByClientId(sessionId);

	MemoryMetaPool.unregisterTopic(httpChannelEntity, topic);

	Set<String> topicSet = MemoryMetaPool
			.getTopicsByChannelEntry(httpChannelEntity);

	Map<String, Object> map = new HashMap<String, Object>(2);
	map.put("status", true);
	map.put("topics", topicSet);
	String result = gson.toJson(map);

	logger.debug("unregister topic = " + topic + " and output = " + result);
	sendFullHttpOKResponse(ctx, req, result);
}
 
開發者ID:osswangxining,項目名稱:mqttserver,代碼行數:27,代碼來源:HttpJsonpTransport.java

示例10: newNonSslHandler

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@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(Names.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
開發者ID:NationalSecurityAgency,項目名稱:qonduit,代碼行數:19,代碼來源:NonSslRedirectHandler.java

示例11: testBasicAuthenticationFailure

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Test
public void testBasicAuthenticationFailure() throws Exception {
    Configuration config = TestConfiguration.createMinimalConfigurationForTest();

    BasicAuthLogin auth = new BasicAuthLogin();
    auth.setUsername("test");
    auth.setPassword("test2");
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
    request.content().writeBytes(JsonSerializer.getObjectMapper().writeValueAsBytes(auth));

    TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Object result = results.iterator().next();
    Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass());

    BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config);
    CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext();
    handler.channelRead(ctx, result);
    Assert.assertNotNull(ctx.msg);
    Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse);
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg;
    Assert.assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
    Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE));
    Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE));
}
 
開發者ID:NationalSecurityAgency,項目名稱:qonduit,代碼行數:27,代碼來源:BasicAuthLoginRequestHandlerTest.java

示例12: sendTextResource

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
private void sendTextResource(String prepend, String name, String mimeType, FullHttpRequest req, ChannelHandlerContext ctx) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader((this.getResourceAsStream(name))));
    // TODO: read only once and buffer
    String line;
    StringBuffer buffer = new StringBuffer();
    if (prepend != null) buffer.append(prepend);
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append('\n');
    }
    ByteBuf content = Unpooled.copiedBuffer(buffer, java.nio.charset.Charset.forName("UTF-8"));

    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

    res.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeType);
    HttpUtil.setContentLength(res, content.readableBytes());

    sendHttpResponse(ctx, req, res);
}
 
開發者ID:satoshinm,項目名稱:WebSandboxMC,代碼行數:20,代碼來源:WebSocketIndexPageHandler.java

示例13: onGetFileChecksum

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
private void onGetFileChecksum(ChannelHandlerContext ctx) throws IOException {
  MD5MD5CRC32FileChecksum checksum = null;
  final String nnId = params.namenodeId();
  DFSClient dfsclient = newDfsClient(nnId, conf);
  try {
    checksum = dfsclient.getFileChecksum(path, Long.MAX_VALUE);
    dfsclient.close();
    dfsclient = null;
  } finally {
    IOUtils.cleanup(LOG, dfsclient);
  }
  final byte[] js = JsonUtil.toJsonString(checksum).getBytes(Charsets.UTF_8);
  DefaultFullHttpResponse resp =
    new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(js));

  resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
  resp.headers().set(CONTENT_LENGTH, js.length);
  resp.headers().set(CONNECTION, CLOSE);
  ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:21,代碼來源:WebHdfsHandler.java

示例14: exceptionCaught

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
  Exception e = cause instanceof Exception ? (Exception) cause : new
    Exception(cause);
  final String output = JsonUtil.toJsonString(e);
  ByteBuf content = Unpooled.wrappedBuffer(output.getBytes(Charsets.UTF_8));
  final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
          HTTP_1_1, INTERNAL_SERVER_ERROR, content);

  resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
  if (e instanceof IllegalArgumentException) {
    resp.setStatus(BAD_REQUEST);
  } else if (e instanceof FileNotFoundException) {
    resp.setStatus(NOT_FOUND);
  }

  resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
  resp.headers().set(CONNECTION, CLOSE);
  ctx.write(resp).addListener(ChannelFutureListener.CLOSE);
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:22,代碼來源:FSImageHandler.java

示例15: channelRead

import io.netty.handler.codec.http.DefaultFullHttpResponse; //導入依賴的package包/類
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
開發者ID:avirtuos,項目名稱:teslog,代碼行數:19,代碼來源:HttpHelloWorldServerHandler.java


注:本文中的io.netty.handler.codec.http.DefaultFullHttpResponse類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。