@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(); } }
/** * 返回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); } }
@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(); } }; }
@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; }
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; }
@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; }
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); } }
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); } }
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"); }
/** * 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; }
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); } }
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); } }
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(); }
@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); } } }
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); } }
private synchronized Collection<FullHttpResponse> sendRequests( final SocketAddress remoteAddress, final Collection<HttpRequest> requests) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(requests.size()); final Collection<FullHttpResponse> content = Collections.synchronizedList(new ArrayList<>(requests.size())); clientBootstrap.handler(new CountDownLatchHandler(latch, content)); ChannelFuture channelFuture = null; try { channelFuture = clientBootstrap.connect(remoteAddress); channelFuture.sync(); for (HttpRequest request : requests) { channelFuture.channel().writeAndFlush(request); } latch.await(10, TimeUnit.SECONDS); } finally { if (channelFuture != null) { channelFuture.channel().close().sync(); } } return content; }
/** * 写入数据到客户端 * * @param messageResult */ public void write(final MessageResult messageResult) { String json = messageResult.toJson(); ByteBuf content = Unpooled.copiedBuffer(json, CharsetUtil.UTF_8); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); // Send the response ChannelFuture f = this.channel.writeAndFlush(res); }
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
@Override public void channelRead0(final ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { inboundChannel.writeAndFlush(msg.retain()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { future.channel().close(); } } }); }
private void sendRedirect(ChannelHandlerContext ctx, String newUri) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND); response.headers().set(HttpHeaderNames.LOCATION, newUri); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
public static void main(String[] args) { NettyHttpClient client=new NettyHttpClient(); long time=System.currentTimeMillis(); HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/baidu?tn=monline_6_dg&ie=utf-8&wd=netty+http客户端"); HttpResponse response=client.syncRequest("www.baidu.com", 80, request); System.out.println(System.currentTimeMillis()-time); System.out.println(response); FullHttpResponse rsp=(FullHttpResponse) response; System.out.println("content:"+rsp.content().toString(CharsetUtil.UTF_8)); // new Scanner(System.in).nextLine(); }
/** * Sets the Date header for the HTTP response * * @param response HTTP response */ private void setDateHeader(FullHttpResponse response) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); Calendar time = new GregorianCalendar(); response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime())); }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { try { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { System.out.println("WebSocket Client failed to connect"); handshakeFuture.setFailure(e); } return; } //发生未知错误 if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); //已收到回复,标记后不再发送音频 ch.attr(AttributeKey.valueOf("response")).set(true); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } }
@Override public FullHttpResponse createResponse(FullHttpRequest aRequest) { String uri = aRequest.uri(); IHttpRequestListener listener = listeners.get(uri); if(listener == null) { String body = aRequest.content().toString(StandardCharsets.UTF_8); return error(uri, body, NOT_FOUND); } return listener.createResponse(aRequest); }
public void sendRedirect(ChannelHandlerContext ctx, String newUri) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND); response.headers().set(HttpHeaders.Names.LOCATION, newUri); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
public void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
/** * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified" * * @param ctx * Context */ public void sendNotModified(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED); setDateHeader(response); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
public ListenableFuture<FullHttpResponse> execute() throws URISyntaxException { Preconditions.checkState(request != null); final SettableFuture<FullHttpResponse> error = SettableFuture.create(); final SettableFuture<FullHttpResponse> response = SettableFuture.create(); final ListenableFuture<ChannelFuture> connectFuture = connect(XUrl.getInetSocket(uri), client.getBootstrap(), buildRetryLoop()); Futures.addCallback( connectFuture, new FutureCallback<ChannelFuture>() { @Override public void onSuccess(ChannelFuture result) { try { Channel channel = result.await().channel(); channel.writeAndFlush(request); HttpResponseHandler responseHandler = (HttpResponseHandler) channel.pipeline().get("responseHandler"); response.setFuture(responseHandler.getResponse()); } catch (InterruptedException e) { response.cancel(true); error.setException(e); } } @Override public void onFailure(Throwable t) { response.cancel(true); error.setException(t); } }); if (response.isCancelled()) { return error; } else { return response; } }
public static void sendResponse(Channel channel, HttpResponseStatus resultCode, ContentTypes contentType, ByteBuf result, boolean isClose) { channel.eventLoop().execute(() -> { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, resultCode, result); response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType.getValue()); response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes() + ""); channel.writeAndFlush(response).addListener((ChannelFutureListener) arg0 -> { if (isClose) { arg0.channel().close(); } }); }); }
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; if (msg instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); } else if (msg instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } else if (msg instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } } }
public void testThatNettyHttpServerSupportsPipelining() throws Exception { String[] requests = new String[]{"/", "/_nodes/stats", "/", "/_cluster/state", "/"}; 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(5)); Collection<String> opaqueIds = Netty4HttpClient.returnOpaqueIds(responses); assertOpaqueIdsInOrder(opaqueIds); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { LOG.info("Received msg: {}", msg); if (!this.handshaker.isHandshakeComplete()) { this.handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg); LOG.info("Client connected."); this.connected = true; this.handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { throw new IllegalStateException("Unexpected response: " + msg.toString()); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { synchronized (responses) { responses.add(((TextWebSocketFrame) frame).text().getBytes(StandardCharsets.UTF_8)); } } else if (frame instanceof BinaryWebSocketFrame) { ByteBuf buf = frame.content(); byte[] b = new byte[buf.readableBytes()]; buf.readBytes(b); synchronized (responses) { responses.add(b); } } else if (frame instanceof PingWebSocketFrame) { LOG.info("Returning pong message"); ctx.writeAndFlush(new PongWebSocketFrame()); } else if (frame instanceof CloseWebSocketFrame) { LOG.info("Received message from server to close the channel."); ctx.close(); } else { LOG.warn("Unhandled frame type received: " + frame.getClass()); } }
public void testLimitsInFlightRequests() throws Exception { ensureGreen(); // we use the limit size as a (very) rough indication on how many requests we should sent to hit the limit int numRequests = LIMIT.bytesAsInt() / 100; StringBuilder bulkRequest = new StringBuilder(); for (int i = 0; i < numRequests; i++) { bulkRequest.append("{\"index\": {}}"); bulkRequest.append(System.lineSeparator()); bulkRequest.append("{ \"field\" : \"value\" }"); bulkRequest.append(System.lineSeparator()); } @SuppressWarnings("unchecked") Tuple<String, CharSequence>[] requests = new Tuple[150]; for (int i = 0; i < requests.length; i++) { requests[i] = Tuple.tuple("/index/type/_bulk", bulkRequest); } HttpServerTransport httpServerTransport = internalCluster().getInstance(HttpServerTransport.class); TransportAddress transportAddress = (TransportAddress) randomFrom(httpServerTransport.boundAddress ().boundAddresses()); try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) { Collection<FullHttpResponse> singleResponse = nettyHttpClient.post(transportAddress.address(), requests[0]); assertThat(singleResponse, hasSize(1)); assertAtLeastOnceExpectedStatus(singleResponse, HttpResponseStatus.OK); Collection<FullHttpResponse> multipleResponses = nettyHttpClient.post(transportAddress.address(), requests); assertThat(multipleResponses, hasSize(requests.length)); assertAtLeastOnceExpectedStatus(multipleResponses, HttpResponseStatus.SERVICE_UNAVAILABLE); } }
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { ByteBuf content = Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, content); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
static Collection<String> returnHttpResponseBodies(Collection<FullHttpResponse> responses) { List<String> list = new ArrayList<>(responses.size()); for (FullHttpResponse response : responses) { list.add(response.content().toString(StandardCharsets.UTF_8)); } return list; }
static Collection<String> returnOpaqueIds(Collection<FullHttpResponse> responses) { List<String> list = new ArrayList<>(responses.size()); for (HttpResponse response : responses) { list.add(response.headers().get("X-Opaque-Id")); } return list; }
public Collection<FullHttpResponse> get(SocketAddress remoteAddress, String... uris) throws InterruptedException { Collection<HttpRequest> requests = new ArrayList<>(uris.length); for (int i = 0; i < uris.length; i++) { final HttpRequest httpRequest = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, uris[i]); httpRequest.headers().add(HOST, "localhost"); httpRequest.headers().add("X-Opaque-ID", String.valueOf(i)); requests.add(httpRequest); } return sendRequests(remoteAddress, requests); }
private Collection<FullHttpResponse> processRequestsWithBody(HttpMethod method, SocketAddress remoteAddress, Tuple<String, CharSequence>... urisAndBodies) throws InterruptedException { Collection<HttpRequest> requests = new ArrayList<>(urisAndBodies.length); for (Tuple<String, CharSequence> uriAndBody : urisAndBodies) { ByteBuf content = Unpooled.copiedBuffer(uriAndBody.v2(), StandardCharsets.UTF_8); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uriAndBody.v1(), content); request.headers().add(HttpHeaderNames.HOST, "localhost"); request.headers().add(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); request.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json"); requests.add(request); } return sendRequests(remoteAddress, requests); }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { try { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { System.out.println("WebSocket Client failed to connect"); handshakeFuture.setFailure(e); } return; } //发生未知错误 if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); } }