遍历http请求参数

博客主要介绍了HTTP请求相关操作,包括遍历请求头、cookie、param和attribute,还涉及获取请求的全路径,对其进行解码并获取其中的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

遍历请求头
Enumeration<String> headerNames = request.getHeaderNames();
if (null != headerNames) {
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        headerMap.put(headerName, headerValue);
        // System.out.println(String.format("%s%s%s%s", "Request Header::", headerName, "=>", headerValue));
    }
}
遍历cookie
Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        CookieVo cookieVo = new CookieVo();
        cookieVo.setComment(cookie.getComment());
        cookieVo.setDomain(cookie.getDomain());
        cookieVo.setHttpOnly(true);
        cookieVo.setMaxAge(cookie.getMaxAge());
        cookieVo.setName(cookie.getName());
        cookieVo.setPath(cookie.getPath());
        cookieVo.setSecure(cookie.getSecure());
        cookieVo.setValue(cookie.getValue());
        cookieVo.setVersion(cookie.getVersion());
        cookiesLists.add(cookieVo);
        // System.out.println(cookie.getValue());
    }
}
遍历param
Enumeration<String> parameterNames = request.getParameterNames();
if (null != parameterNames) {
    while (parameterNames.hasMoreElements()) {
        String parameterName = parameterNames.nextElement();
        String parameterValue = request.getParameter(parameterName);
        requestMap.put(parameterName, parameterValue);
        // System.out.println(String.format("%s%s%s%s", "Request Parameter::", parameterName, "=>", parameterValue));
    }
}
遍历attribute
Enumeration<String> attributeNames = request.getAttributeNames();
if (null != attributeNames) {
    while (attributeNames.hasMoreElements()) {
        String attributeName = attributeNames.nextElement();
        String attributeValue = request.getAttribute(attributeName).toString();
        attributeMap.put(attributeName, attributeValue);
        // System.out.println(String.format("%s%s%s%s", "Request Attribute::", attributeName, "=>", attributeValue));
    }
}
获取请求的全路径,解码,获取其中的参数
StringBuffer requestURL = request.getRequestURL();
String queryString = request.getQueryString();
String url = requestURL.toString() + "?" + queryString;
@SuppressWarnings("deprecation")
String decodeUrl = URLDecoder.decode(url);
urlParam = this.queryString(decodeUrl);
private Map<String, Object> queryString(String urlStr) {
    Map<String, Object> queryMap = new HashMap<>();
    URL url;
    try {
        url = new URL(urlStr);
        String queryStr = url.getQuery();
        String[] queryArr = queryStr.split("[&]");
        for (String queryItem : queryArr) {
            String[] arrSplitEqual = null;
            arrSplitEqual = queryItem.split("[=]");
            if (arrSplitEqual.length > 1) {
                queryMap.put(arrSplitEqual[0], queryItem.substring(arrSplitEqual[0].length() + 1));
            } else {
                if (arrSplitEqual[0] != "") {
                    queryMap.put(arrSplitEqual[0], "");
                }
            }
        }
        return queryMap;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return queryMap;
}
### 实现遍历 Cookie 进行多次请求 为了在 JMeter 中实现遍历 Cookie 并针对每个 Cookie 发起多次 HTTP 请求,可以采用如下最佳实践方案: #### 使用 CSV Data Set Config 或者自定义 BeanShell PreProcessor 提取 Cookies 当需要遍历一组预设的 Cookies 时,可以通过 `CSV Data Set Config` 组件来读取存储于文件内的 Cookie 数据。对于动态获取的 Cookies,则适合利用 `BeanShell PreProcessor` 结合 vars 对象操作线程中的局部变量容器[^1]。 ```properties cookieFile=cookies.csv variableNames=COOKIE_NAME,COOKIE_VALUE delimiter=, recycle=false stopThread=false shareMode=all_threads ``` 上述配置展示了如何通过 `CSV Data Set Config` 加载外部 CSV 文件作为 Cookie 的输入源。每列分别对应不同的属性名称和对应的值。 #### 动态构建 HTTP Header Manager 添加 Cookie 参数 一旦获得了单个或多个 Cookies 后,在每次迭代之前都需要更新即将发出的 HTTP 请求头信息里的 Cookie 字段。这一步骤可通过 `User Defined Variables` 和 `${__V}` 函数配合完成,也可以直接编写脚本逻辑放在 `BeanShell PreProcessor` 内部执行。 ```java // 获取当前线程上下文中保存的所有Cookies String cookies = vars.get("ALL_COOKIES"); if (cookies != null && !"".equals(cookies.trim())) { // 将字符串形式的Cookies转换成数组并循环处理每一个Cookie项 String[] cookieArray = cookies.split("; "); StringBuilder sb = new StringBuilder(); for(String c : cookieArray){ if(sb.length()>0)sb.append("; "); sb.append(c); } // 更新HTTP Header Manager中的Cookie字段 sampler.getHeaderManager().add(new Header("Cookie",sb.toString())); } ``` 这段代码片段说明了怎样借助 `BeanShell PreProcessor` 修改即将发送出去的 HTTP 请求头部携带特定格式化的 Cookie 串。 #### 设置合适的控制器以支持多轮次调用 为了让整个流程能够按照预期顺序工作,还需要合理安排好各个组件之间的层次关系及其内部参数设定。特别是要关注 `Loop Controller` 及其子节点下的采样器数量、计数方式等细节之处[^2]。 ```xml <elementProp name="loop_control" elementType="LoopController"> <boolProp name="LoopController.continue_forever">false</boolProp> <stringProp name="LoopController.loops">${__P(loopsCount,5)}</stringProp> </elementProp> ``` 此 XML 片段描述了一个简单的 Loop 控制策略,默认情况下会重复五次;当然也允许用户通过命令行传递参数来自定义次数。 #### 注意事项与调试技巧 考虑到实际场景复杂度较高,建议开启 Debug Sampler 来捕获中间状态变化情况以便后续分析排查问题所在。另外需要注意的是某些特殊字符可能会引起解析错误因此务必遵循正确的语法规范[^3]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值