com.yuyenews.easy.server.request.RequestParser Maven / Gradle / Ivy
The newest version!
package com.yuyenews.easy.server.request;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import com.yuyenews.easy.server.request.model.FileUpLoad;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MixedFileUpload;
/**
* 参数解析器
*
* @author yuye
*
*/
public class RequestParser {
private FullHttpRequest fullReq;
/**
* 构造一个解析器
*
* @param req 请求对象
*/
public RequestParser(FullHttpRequest req) {
this.fullReq = req;
}
/**
* 解析请求参数
*
* @return 包含所有请求参数的键值对, 如果没有参数, 则返回空Map
*
* @throws IOException 异常
*/
@SuppressWarnings("unchecked")
public Map parse() throws IOException {
HttpMethod method = fullReq.method();
Map parmMap = new HashMap<>();
if (HttpMethod.GET == method) {
// 是GET请求
QueryStringDecoder decoder = new QueryStringDecoder(fullReq.uri());
decoder.parameters().entrySet().forEach(entry -> {
parmMap.put(entry.getKey(), entry.getValue());
});
} else if (HttpMethod.POST == method) {
// 是POST请求
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullReq);
decoder.offer(fullReq);
List parmList = decoder.getBodyHttpDatas();
Map files = new Hashtable<>();
for (InterfaceHttpData parm : parmList) {
if (parm instanceof Attribute) {
Attribute data = (Attribute) parm;
List