下面列出了 io.netty.handler.codec.http.FullHttpRequest # content ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 请求分发与处理
*
* @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;
}
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());
}
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();
}
}
}
}
}
}
}
@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);
}
}
@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();
}
}
@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();
}
}
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();
}
protected byte[] getContentByMsg(final FullHttpRequest msg) {
ByteBuf buf = msg.content();
int size = buf.readableBytes();
byte[] s1 = new byte[size];
buf.readBytes(s1);
return s1;
}
@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);
}
@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);
}
@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;
}
}
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());
}
}
}
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) ;
}
/**
* 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);
}
}
}
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;
}
public InputStreamImpl(FullHttpRequest request) {
this.in = new ByteBufInputStream(request.content());
}
/** 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()));
}
/**
* 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);
}
}
}
/**
* 获取body参数
* @param request
* @return
*/
private String getBody(FullHttpRequest request){
ByteBuf buf = request.content();
return buf.toString(CharsetUtil.UTF_8);
}