java请求获取参数

//get请求获取参数
public String getParamters(HttpServletRequest request) {
    Map<String, String> map = Maps.newHashMap();
    Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String key = parameterNames.nextElement();
        String value = request.getParameter(key);
        map.put(key, value);
    }
    LinkedHashMap attribute = (LinkedHashMap) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    Set<Map.Entry<String, String>> entrySet = attribute.entrySet();
    for (Map.Entry<String, String> entry : entrySet) {
        map.put(entry.getKey(), entry.getValue());
    }

    return map.toString();
}

//post请求获取参数
public String getBodyString(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();
    InputStream inputStream = null;
    BufferedReader reader = null;
    try {
        inputStream = request.getInputStream();
        reader = new BufferedReader(
                new InputStreamReader(inputStream, Charset.forName(Constants.CHAREST_CODE)));

        char[] bodyCharBuffer = new char[1024];
        int len = 0;
        while ((len = reader.read(bodyCharBuffer)) != -1) {
            sb.append(new String(bodyCharBuffer, 0, len));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return sb.toString();
}

if ("GET".equals(method)) {
    paramSb.append(getParamters(request));
} else if ("POST".equals(method)) {
    paramSb.append(getBodyString(request));
} else if ("PUT".equals(method)) {
    paramSb.append(getBodyString(request));
} else if ("DELETE".equals(method)) {
    paramSb.append(getParamters(request));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值