本文整理汇总了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();
}
示例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();
}
}
示例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);
}
}
示例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();
}
};
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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");
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
}
示例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);
}
}