Java Code Examples for io.netty.handler.codec.http.FullHttpRequest#content()
The following examples show how to use
io.netty.handler.codec.http.FullHttpRequest#content() .
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: SqlHttpHandler.java From crate with Apache License 2.0 | 6 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { if (request.uri().startsWith("/_sql")) { Session session = ensureSession(request); Map<String, List<String>> parameters = new QueryStringDecoder(request.uri()).parameters(); ByteBuf content = request.content(); handleSQLRequest(session, content, paramContainFlag(parameters, "types")) .whenComplete((result, t) -> { try { sendResponse(session, ctx, request, parameters, result, t); } catch (Throwable ex) { LOGGER.error("Error sending response", ex); throw ex; } finally { request.release(); } }); } else { ctx.fireChannelRead(request); } }
Example 2
Source File: ServletNettyChannelHandler.java From netty-cookbook with Apache License 2.0 | 6 votes |
void copyHttpBodyData(FullHttpRequest fullHttpReq, MockHttpServletRequest servletRequest){ ByteBuf bbContent = fullHttpReq.content(); if(bbContent.hasArray()) { servletRequest.setContent(bbContent.array()); } else { if(fullHttpReq.getMethod().equals(HttpMethod.POST)){ HttpPostRequestDecoder decoderPostData = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpReq); String bbContentStr = bbContent.toString(Charset.forName(UTF_8)); servletRequest.setContent(bbContentStr.getBytes()); if( ! decoderPostData.isMultipart() ){ List<InterfaceHttpData> postDatas = decoderPostData.getBodyHttpDatas(); for (InterfaceHttpData postData : postDatas) { if (postData.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute) postData; try { servletRequest.addParameter(attribute.getName(),attribute.getValue()); } catch (IOException e) { e.printStackTrace(); } } } } } } }
Example 3
Source File: HttpDecoder.java From ffwd with Apache License 2.0 | 6 votes |
private void postBatch( final ChannelHandlerContext ctx, final FullHttpRequest in, final List<Object> out ) { final Batch batch; try (final InputStream inputStream = new ByteBufInputStream(in.content())) { batch = mapper.readValue(inputStream, Batch.class); } catch (final IOException e) { log.error("HTTP Bad Request", e); throw new HttpException(HttpResponseStatus.BAD_REQUEST); } out.add(batch); ctx .channel() .writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)) .addListener((ChannelFutureListener) future -> future.channel().close()); }
Example 4
Source File: DefaultDispatcher.java From ace with Apache License 2.0 | 6 votes |
/** * 请求分发与处理 * * @param request http协议请求 * @return 处理结果 * @throws InvocationTargetException 调用异常 * @throws IllegalAccessException 参数异常 */ public Object doDispatcher(FullHttpRequest request) throws InvocationTargetException, IllegalAccessException { Object[] args; String uri = request.uri(); if (uri.endsWith("favicon.ico")) { return ""; } AceServiceBean aceServiceBean = Context.getAceServiceBean(uri); AceHttpMethod aceHttpMethod = AceHttpMethod.getAceHttpMethod(request.method().toString()); ByteBuf content = request.content(); //如果要多次解析,请用 request.content().copy() QueryStringDecoder decoder = new QueryStringDecoder(uri); Map<String, List<String>> requestMap = decoder.parameters(); Object result = aceServiceBean.exec(uri, aceHttpMethod, requestMap, content == null ? null : content.toString(CharsetUtil.UTF_8)); String contentType = request.headers().get("Content-Type"); if (result == null) { ApplicationInfo mock = new ApplicationInfo(); mock.setName("ace"); mock.setVersion("1.0"); mock.setDesc(" mock !!! "); result = mock; } return result; }
Example 5
Source File: HttpHandler.java From netty-pubsub with MIT License | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { // TODO Auto-generated method stub try { ByteBuf content = msg.content(); byte[] bts = new byte[content.readableBytes()]; content.readBytes(bts); String result = null; if(msg.getMethod() == HttpMethod.GET) { String url = msg.getUri().toString(); result =JSON.toJSONString(UrlUtil.parse(url).params); doGet(result); }else if(msg.getMethod() == HttpMethod.POST) { //result = "post method and paramters is "+ new String(bts); doPost(new String(bts,"utf-8")); } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set("content-Type","text/html;charset=UTF-8"); StringBuilder sb = new StringBuilder(); sb.append("OK"); ByteBuf responseBuf = Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8); response.content().writeBytes(responseBuf); responseBuf.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }catch (Exception e) { e.printStackTrace(); } }
Example 6
Source File: JSONMessageRouteHandler.java From Sparkngin with GNU Affero General Public License v3.0 | 5 votes |
protected void doPost(ChannelHandlerContext ctx, HttpRequest httpReq) { FullHttpRequest req = (FullHttpRequest) httpReq ; ByteBuf byteBuf = req.content() ; byte[] data = new byte[byteBuf.readableBytes()] ; byteBuf.readBytes(data) ; byteBuf.release() ; Message message = JSONSerializer.INSTANCE.fromBytes(data, Message.class) ; Ack ack = sparkngin.push(message); writeJSON(ctx, httpReq, ack) ; }
Example 7
Source File: FunctionsChannelHandler.java From netty-cookbook with Apache License 2.0 | 5 votes |
void copyHttpBodyData(FullHttpRequest fullHttpReq, SimpleHttpRequest req){ ByteBuf bbContent = fullHttpReq.content(); if(bbContent.hasArray()) { req.setBody(bbContent.array()); } else { if(fullHttpReq.getMethod().equals(HttpMethod.POST)){ String bbContentStr = bbContent.toString(Charset.forName("UTF-8")); req.setBody(bbContentStr.getBytes()); } } }
Example 8
Source File: AsyncHttpCaller.java From pampas with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Response> asyncCall(AsyncHttpRequest req, ServerInstance serverInstance) { final FullHttpRequest httpRequest = req.getFullHttpRequest(); try { final AsyncHttpClient httpClient = this.client; BoundRequestBuilder requestBuilder = new BoundRequestBuilder(httpClient, httpRequest.method().name(), true); requestBuilder.setUri(Uri.create(serverInstance.toUri() + req.getRequestPath())); for (Map.Entry<String, String> headerEntry : httpRequest.headers()) { if (StringUtils.isNotEmpty(headerEntry.getKey()) && !"Host".equals(headerEntry.getKey())) { requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } requestBuilder.addHeader(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); if (httpRequest.content() != null && httpRequest.content().isReadable()) { //请求body转换为ByteBuffer,并且设置为只读,ByteBuf复用 堆内存中的数据 zero copy ByteBuffer readOnlyBuffer = httpRequest.content().nioBuffer().asReadOnlyBuffer(); requestBuilder.setBody(readOnlyBuffer); } ListenableFuture<Response> listenableFuture = requestBuilder.execute(); return listenableFuture.toCompletableFuture(); } catch (Exception ex) { log.warn("执行调用报错:{}", ex); CompletableFuture<Response> exceptionFuture = CompletableFuture.completedFuture(null); exceptionFuture.completeExceptionally(ex); return exceptionFuture; } }
Example 9
Source File: HttpServerHandler.java From cantor with Apache License 2.0 | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (FullHttpRequest.class.isAssignableFrom(msg.getClass())) { FullHttpRequest req = FullHttpRequest.class.cast(msg); DecoderResult result = req.decoderResult(); if (result.isFailure()) { if (log.isWarnEnabled()) log.warn("http decoder failure", result.cause()); ReferenceCountUtil.release(msg); ctx.writeAndFlush(HttpResponses.badRequest()); ctx.channel().close(); return; } if (HttpUtil.is100ContinueExpected(req)) ctx.writeAndFlush(new DefaultFullHttpResponse(req.protocolVersion(), CONTINUE)); FullHttpRequest safeReq = new DefaultFullHttpRequest(req.protocolVersion(), req.method(), req.uri(), // Buffers.safeByteBuf(req.content(), ctx.alloc()), req.content(), req.headers(), req.trailingHeaders()); channelRead(ctx, safeReq); } else ctx.fireChannelRead(msg); }
Example 10
Source File: RpcxHttpHandler.java From rpcx-java with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) { String servicePath = msg.headers().get(Constants.X_RPCX_SERVICEPATH); String serviceMethod = msg.headers().get(Constants.X_RPCX_SERVICEMETHOD); String traceId = msg.headers().get(Constants.X_RPCX_TRACEID); logger.info("service:{} method:{} traceId:{}", servicePath, serviceMethod, traceId); ByteBuf buf = msg.content(); int len = buf.readableBytes(); byte[] payload = new byte[len]; buf.readBytes(payload); Message message = new Message(); message.metadata.put("language", LanguageCode.HTTP.name()); message.metadata.put("_host", getClientIp(ctx, msg)); message.metadata.put("_port", "0"); message.metadata.put(Constants.X_RPCX_TRACEID, traceId == null ? "" : traceId); message.servicePath = servicePath; message.serviceMethod = serviceMethod; message.payload = payload; message.setMessageType(MessageType.Request); message.setOneway(true); RemotingCommand command = RemotingCommand.createRequestCommand(message); command.setCode(1984); //这里会异步处理 nettyServer.processRequestCommand(ctx, command); }
Example 11
Source File: SimpleHttpBizHandler.java From joyrpc with Apache License 2.0 | 5 votes |
protected byte[] getContentByMsg(final FullHttpRequest msg) { ByteBuf buf = msg.content(); int size = buf.readableBytes(); byte[] s1 = new byte[size]; buf.readBytes(s1); return s1; }
Example 12
Source File: HttpTestServerHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
private static String formatContent(FullHttpRequest request) { String header = HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_TYPE); StringBuffer bf = new StringBuffer(); if (HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.equalsIgnoreCase(header)) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request); List<InterfaceHttpData> data = decoder.getBodyHttpDatas(); if (data != null) { for (InterfaceHttpData datum : data) { if (datum.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute)datum; try { bf.append(attribute.getName()).append(" -> ").append(attribute.getString()).append("\n"); } catch (IOException e) { e.printStackTrace(); } } } } else { bf.append("[No Data]\n"); } } else if ("application/json".equalsIgnoreCase(header)) { ByteBuf byteBuf = request.content(); byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); String s = new String(bytes, StandardCharsets.UTF_8); bf.append(s); } else { bf.append("[Unknown Data Type ").append(header).append("]"); } return bf.toString(); }
Example 13
Source File: TestHttp.java From netty-pubsub with MIT License | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { // TODO Auto-generated method stub try { ByteBuf content = msg.content(); byte[] bts = new byte[content.readableBytes()]; content.readBytes(bts); String result = null; if(msg.getMethod() == HttpMethod.GET) { String url = msg.getUri().toString(); //result = "get method and paramters is "+JSON.toJSONString(UrlUtil.parse(url).params); }else if(msg.getMethod() == HttpMethod.POST) { result = "post method and paramters is "+ new String(bts); } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set("content-Type","text/html;charset=UTF-8"); StringBuilder sb = new StringBuilder(); sb.append("<html>") .append("<head>") .append("<title>netty http server</title>") .append("</head>") .append("<body>") .append(result) .append("</body>") .append("</html>\r\n"); ByteBuf responseBuf = Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8); response.content().writeBytes(responseBuf); responseBuf.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }catch (Exception e) { e.printStackTrace(); } }
Example 14
Source File: AgentHandler.java From vlingo-http with Mozilla Public License 2.0 | 4 votes |
private Request toConsumable(final FullHttpRequest request) throws Exception { final Method consumableMethod = Method.from(request.method().name()); final URI consumableURI = new URI(request.uri()); final Version consumableVersion = Version.Http1_1; final Headers<RequestHeader> headers = Headers.empty(); for (final Map.Entry<String, String> entry : request.headers()) { final RequestHeader header = RequestHeader.of(entry.getKey(), entry.getValue()); headers.add(header); } final ByteBuf content = request.content(); final Body body = content.isReadable() ? Body.from(content.toString(CharsetUtil.UTF_8)) : Body.Empty; final Request consumableRequest = Request.from(consumableMethod, consumableURI, consumableVersion, headers, body); // logger.debug(">>>>> AgentHandler::toConsumable(): " + instanceId + " NAME: " + contextInstanceId + " : REQUEST:\n" + consumableRequest); return consumableRequest; }
Example 15
Source File: InputStreamImpl.java From dorado with Apache License 2.0 | 4 votes |
public InputStreamImpl(FullHttpRequest request) { this.in = new ByteBufInputStream(request.content()); }
Example 16
Source File: HttpRequestMessage.java From nomulus with Apache License 2.0 | 4 votes |
/** Used for conversion from {@link FullHttpRequest} to {@link HttpRequestMessage} */ public HttpRequestMessage(FullHttpRequest request) { this(request.protocolVersion(), request.method(), request.uri(), request.content()); request.headers().forEach((entry) -> headers().set(entry.getKey(), entry.getValue())); }
Example 17
Source File: HttpPostRequestEncoder.java From netty4.0.27Learn with Apache License 2.0 | 4 votes |
/** * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br> * Once finalized, no data must be added.<br> * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote * server. * * @return the request object (chunked or not according to size of body) * @throws ErrorDataEncoderException * if the encoding is in error or if the finalize were already done */ public HttpRequest finalizeRequest() throws ErrorDataEncoderException { // Finalize the multipartHttpDatas if (!headerFinalized) { if (isMultipart) { InternalAttribute internal = new InternalAttribute(charset); if (duringMixedMode) { internal.addValue("\r\n--" + multipartMixedBoundary + "--"); } internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n"); multipartHttpDatas.add(internal); multipartMixedBoundary = null; currentFileUpload = null; duringMixedMode = false; globalBodySize += internal.size(); } headerFinalized = true; } else { throw new ErrorDataEncoderException("Header already encoded"); } HttpHeaders headers = request.headers(); List<String> contentTypes = headers.getAll(HttpHeaders.Names.CONTENT_TYPE); List<String> transferEncoding = headers.getAll(HttpHeaders.Names.TRANSFER_ENCODING); if (contentTypes != null) { headers.remove(HttpHeaders.Names.CONTENT_TYPE); for (String contentType : contentTypes) { // "multipart/form-data; boundary=--89421926422648" String lowercased = contentType.toLowerCase(); if (lowercased.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA) || lowercased.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED)) { // ignore } else { headers.add(HttpHeaders.Names.CONTENT_TYPE, contentType); } } } if (isMultipart) { String value = HttpHeaders.Values.MULTIPART_FORM_DATA + "; " + HttpHeaders.Values.BOUNDARY + '=' + multipartDataBoundary; headers.add(HttpHeaders.Names.CONTENT_TYPE, value); } else { // Not multipart headers.add(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); } // Now consider size for chunk or not long realSize = globalBodySize; if (isMultipart) { iterator = multipartHttpDatas.listIterator(); } else { realSize -= 1; // last '&' removed iterator = multipartHttpDatas.listIterator(); } headers.set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(realSize)); if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) { isChunked = true; if (transferEncoding != null) { headers.remove(HttpHeaders.Names.TRANSFER_ENCODING); for (String v : transferEncoding) { if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) { // ignore } else { headers.add(HttpHeaders.Names.TRANSFER_ENCODING, v); } } } HttpHeaders.setTransferEncodingChunked(request); // wrap to hide the possible content return new WrappedHttpRequest(request); } else { // get the only one body and set it to the request HttpContent chunk = nextChunk(); if (request instanceof FullHttpRequest) { FullHttpRequest fullRequest = (FullHttpRequest) request; ByteBuf chunkContent = chunk.content(); if (fullRequest.content() != chunkContent) { fullRequest.content().clear().writeBytes(chunkContent); chunkContent.release(); } return fullRequest; } else { return new WrappedFullHttpRequest(request, chunk); } } }
Example 18
Source File: HttpPostRequestEncoder.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
/** * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br> * Once finalized, no data must be added.<br> * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote * server.通过准备请求中的标头完成请求,并返回准备发送的请求。一旦确定,就不需要添加任何数据。如果请求不需要chunk (isChunked() == false),此请求是发送到远程服务器的唯一对象。 * * @return the request object (chunked or not according to size of body) * @throws ErrorDataEncoderException * if the encoding is in error or if the finalize were already done */ public HttpRequest finalizeRequest() throws ErrorDataEncoderException { // Finalize the multipartHttpDatas if (!headerFinalized) { if (isMultipart) { InternalAttribute internal = new InternalAttribute(charset); if (duringMixedMode) { internal.addValue("\r\n--" + multipartMixedBoundary + "--"); } internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n"); multipartHttpDatas.add(internal); multipartMixedBoundary = null; currentFileUpload = null; duringMixedMode = false; globalBodySize += internal.size(); } headerFinalized = true; } else { throw new ErrorDataEncoderException("Header already encoded"); } HttpHeaders headers = request.headers(); List<String> contentTypes = headers.getAll(HttpHeaderNames.CONTENT_TYPE); List<String> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING); if (contentTypes != null) { headers.remove(HttpHeaderNames.CONTENT_TYPE); for (String contentType : contentTypes) { // "multipart/form-data; boundary=--89421926422648" String lowercased = contentType.toLowerCase(); if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) || lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) { // ignore } else { headers.add(HttpHeaderNames.CONTENT_TYPE, contentType); } } } if (isMultipart) { String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '=' + multipartDataBoundary; headers.add(HttpHeaderNames.CONTENT_TYPE, value); } else { // Not multipart headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED); } // Now consider size for chunk or not long realSize = globalBodySize; if (isMultipart) { iterator = multipartHttpDatas.listIterator(); } else { realSize -= 1; // last '&' removed iterator = multipartHttpDatas.listIterator(); } headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize)); if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) { isChunked = true; if (transferEncoding != null) { headers.remove(HttpHeaderNames.TRANSFER_ENCODING); for (CharSequence v : transferEncoding) { if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(v)) { // ignore } else { headers.add(HttpHeaderNames.TRANSFER_ENCODING, v); } } } HttpUtil.setTransferEncodingChunked(request, true); // wrap to hide the possible content return new WrappedHttpRequest(request); } else { // get the only one body and set it to the request HttpContent chunk = nextChunk(); if (request instanceof FullHttpRequest) { FullHttpRequest fullRequest = (FullHttpRequest) request; ByteBuf chunkContent = chunk.content(); if (fullRequest.content() != chunkContent) { fullRequest.content().clear().writeBytes(chunkContent); chunkContent.release(); } return fullRequest; } else { return new WrappedFullHttpRequest(request, chunk); } } }
Example 19
Source File: NettyServerHandler.java From java-study with Apache License 2.0 | 2 votes |
/** * 获取body参数 * @param request * @return */ private String getBody(FullHttpRequest request){ ByteBuf buf = request.content(); return buf.toString(CharsetUtil.UTF_8); }