当前位置: 首页>>代码示例>>Java>>正文


Java FullHttpResponse类代码示例

本文整理汇总了Java中io.netty.handler.codec.http.FullHttpResponse的典型用法代码示例。如果您正苦于以下问题:Java FullHttpResponse类的具体用法?Java FullHttpResponse怎么用?Java FullHttpResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


FullHttpResponse类属于io.netty.handler.codec.http包,在下文中一共展示了FullHttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: writeBack

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的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: channelRead0

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
@Override
public void channelRead0(ChannelHandlerContext context, Object message) throws Exception {
  Channel channel = context.channel();
  if (message instanceof FullHttpResponse) {
    checkState(!handshaker.isHandshakeComplete());
    try {
      handshaker.finishHandshake(channel, (FullHttpResponse) message);
      delegate.onOpen();
    } catch (WebSocketHandshakeException e) {
      delegate.onError(e);
    }
  } else if (message instanceof TextWebSocketFrame) {
    delegate.onMessage(((TextWebSocketFrame) message).text());
  } else {
    checkState(message instanceof CloseWebSocketFrame);
    delegate.onClose();
  }
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:19,代码来源:NettyWebSocketClient.java

示例3: sendHttpResponse

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
/**
 * 返回http信息
 * @param ctx
 * @param req
 * @param res
 */
private static void sendHttpResponse(
        ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
开发者ID:ninelook,项目名称:wecard-server,代码行数:23,代码来源:NettyServerHandler.java

示例4: newNonSslHandler

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的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

示例5: response

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
@Override
public FullHttpResponse response(){
	if(response==null) {
		switch (renderType) {
			case JSON:
				response = HttpRenderUtil.renderJSON(bytes);
				break;
			case TEXT:
				response = HttpRenderUtil.renderText(bytes);
				break;
			case XML:
				response = HttpRenderUtil.renderXML(bytes);
				break;
			case HTML:
				response = HttpRenderUtil.renderHTML(bytes);
				break;
			default:
				response = HttpRenderUtil.getServerErrorResponse();
				logger.error("unknown response type");
		}
	}
	return response;
}
 
开发者ID:all4you,项目名称:redant,代码行数:24,代码来源:DefaultRender.java

示例6: writeResponse

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的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

示例7: get

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的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

示例8: sendHttpResponse

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
private static void sendHttpResponse(ChannelHandlerContext ctx,
		HttpRequest req, FullHttpResponse res) {
	// Generate an error page if response getStatus code is not OK (200).
	if (res.getStatus().code() != 200) {
		ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
				CharsetUtil.UTF_8);
		res.content().writeBytes(buf);
		buf.release();
		setContentLength(res, res.content().readableBytes());
	}

	// Send the response and close the connection if necessary.
	ChannelFuture f = ctx.writeAndFlush(res);
	if (!isKeepAlive(req) || res.getStatus().code() != 200) {
		f.addListener(ChannelFutureListener.CLOSE);
	}
}
 
开发者ID:osswangxining,项目名称:mqttserver,代码行数:18,代码来源:HttpJsonpTransport.java

示例9: sendHttpResponse

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
开发者ID:SpreadServe,项目名称:TFWebSock,代码行数:17,代码来源:NettyHttpFileHandler.java

示例10: getDino

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
private static FullHttpResponse getDino(XrpcRequest request, List<Dino> dinos) {
  try {
    DinoGetRequest getRequest =
        DinoGetRequest.parseFrom(CodedInputStream.newInstance(request.getData().nioBuffer()));
    Optional<Dino> dinoOptional =
        dinos.stream().filter(xs -> xs.getName().equals(getRequest.getName())).findFirst();

    if (dinoOptional.isPresent()) {
      DinoGetReply getReply = DinoGetReply.newBuilder().setDino(dinoOptional.get()).build();
      ByteBuf resp = request.getByteBuf();
      resp.ensureWritable(CodedOutputStream.computeMessageSizeNoTag(getReply), true);
      getReply.writeTo(new ByteBufOutputStream(resp));

      return Recipes.newResponse(
          HttpResponseStatus.OK,
          request.getByteBuf().writeBytes(resp),
          Recipes.ContentType.Application_Octet_Stream);
    }

  } catch (IOException e) {
    return Recipes.newResponseBadRequest("Malformed GetDino Request: " + e.getMessage());
  }

  return Recipes.newResponseOk("Dino not Found");
}
 
开发者ID:Nordstrom,项目名称:xrpc,代码行数:26,代码来源:Example.java

示例11: newResponse

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的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

示例12: testThatNettyHttpServerDoesNotSupportPipelining

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
public void testThatNettyHttpServerDoesNotSupportPipelining() throws Exception {
    ensureGreen();
    String[] requests = new String[] {"/", "/_nodes/stats", "/", "/_cluster/state", "/", "/_nodes", "/"};

    HttpServerTransport httpServerTransport = internalCluster().getInstance(HttpServerTransport.class);
    TransportAddress[] boundAddresses = httpServerTransport.boundAddress().boundAddresses();
    TransportAddress transportAddress = (TransportAddress) randomFrom(boundAddresses);

    try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) {
        Collection<FullHttpResponse> responses = nettyHttpClient.get(transportAddress.address(), requests);
        assertThat(responses, hasSize(requests.length));

        List<String> opaqueIds = new ArrayList<>(Netty4HttpClient.returnOpaqueIds(responses));

        assertResponsesOutOfOrder(opaqueIds);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:Netty4PipeliningDisabledIT.java

示例13: testDoesNotLimitExcludedRequests

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
public void testDoesNotLimitExcludedRequests() throws Exception {
    ensureGreen();

    @SuppressWarnings("unchecked")
    Tuple<String, CharSequence>[] requestUris = new Tuple[1500];
    for (int i = 0; i < requestUris.length; i++) {
        requestUris[i] = Tuple.tuple("/_cluster/settings",
            "{ \"transient\": {\"search.default_search_timeout\": \"40s\" } }");
    }

    HttpServerTransport httpServerTransport = internalCluster().getInstance(HttpServerTransport.class);
    TransportAddress transportAddress = (TransportAddress) randomFrom(httpServerTransport.boundAddress
        ().boundAddresses());

    try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) {
        Collection<FullHttpResponse> responses = nettyHttpClient.put(transportAddress.address(), requestUris);
        assertThat(responses, hasSize(requestUris.length));
        assertAllInExpectedStatus(responses, HttpResponseStatus.OK);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:Netty4HttpRequestSizeLimitIT.java

示例14: channelRead

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的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

示例15: executeRequest

import io.netty.handler.codec.http.FullHttpResponse; //导入依赖的package包/类
private FullHttpResponse executeRequest(final Settings settings, final String originValue, final String host) {
    // construct request and send it over the transport layer
    try (Netty4HttpServerTransport httpServerTransport =
                 new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(),
                         new NullDispatcher())) {
        httpServerTransport.start();
        final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        if (originValue != null) {
            httpRequest.headers().add(HttpHeaderNames.ORIGIN, originValue);
        }
        httpRequest.headers().add(HttpHeaderNames.HOST, host);
        final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel();
        final Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel);

        Netty4HttpChannel channel =
                new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext());
        channel.sendResponse(new TestResponse());

        // get the response
        List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects();
        assertThat(writtenObjects.size(), is(1));
        return (FullHttpResponse) writtenObjects.get(0);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:Netty4HttpChannelTests.java


注:本文中的io.netty.handler.codec.http.FullHttpResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。