JMeter中Java代码设置Content-Type被覆盖的问题及解决
问题解决:JMeter中Content-Type被覆盖为text/plain的处理方法
根本原因
当JMeter的HTTPSamplerProxy发送包含请求体的POST请求时,会自动生成并设置Content-Type: text/plain,这个设置的优先级高于HeaderManager中配置的内容,导致自定义的application/json被覆盖。
解决方案
需要直接在HTTPSamplerProxy实例中指定Content-Type,并配置请求体为原始JSON格式,具体修改如下:
1. 修改HTTPSamplerProxy核心配置
在创建HTTPSamplerProxy的代码块中,添加以下关键配置:
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy(); httpSampler.setProtocol("https"); httpSampler.setDomain(config.getString("JMETER_DOMAIN")); httpSampler.setPath(api); httpSampler.setMethod(method); // 强制指定Content-Type并启用原始请求体发送 httpSampler.setContentType("application/json"); httpSampler.setPostBodyRaw(true); // 发送原始JSON字符串,而非表单编码格式
2. 正确设置JSON请求体
如果请求需要携带JSON内容,通过Arguments类正确传递请求体:
// 替换为你的实际JSON请求内容 String jsonBody = "{\"username\":\"test\",\"password\":\"123456\"}"; Arguments arguments = new Arguments(); // 第一个参数留空,第二个参数为JSON内容,第三个参数指定MIME类型 arguments.addArgument("", jsonBody, "application/json"); httpSampler.setArguments(arguments);
3. 保留HeaderManager配置(可选)
如果需要通过HeaderManager管理其他请求头,可保留原有代码,此时Content-Type会以HTTPSamplerProxy中设置的为准,不会被覆盖。
修改后的完整代码片段
HeaderManager headerManager = new HeaderManager(); // 可保留其他Header配置,Content-Type由Sampler指定即可 // headerManager.add(createHeader("Content-Type", "application/json")); HTTPSamplerProxy httpSampler = new HTTPSamplerProxy(); httpSampler.setProtocol("https"); httpSampler.setDomain(config.getString("JMETER_DOMAIN")); httpSampler.setPath(api); httpSampler.setMethod(method); // 关键配置 httpSampler.setContentType("application/json"); httpSampler.setPostBodyRaw(true); // 设置JSON请求体 String jsonBody = "{\"username\":\"test\",\"password\":\"123456\"}"; Arguments arguments = new Arguments(); arguments.addArgument("", jsonBody, "application/json"); httpSampler.setArguments(arguments); TestPlan testPlan = new TestPlan("MY TEST PLAN"); // 组装测试计划树 ListedHashTree testPlanTree = new ListedHashTree(); testPlanTree.add(testPlan); ListedHashTree threadGroupTree = new ListedHashTree(threadGroup); threadGroupTree.add(httpSampler,headerManager); testPlanTree.add(testPlan, threadGroupTree); // 执行测试 jm.configure(testPlanTree); jm.run();
验证效果
修改后重新执行测试,查看请求日志,Content-Type会被正确设置为application/json,服务端将返回正常响应而非415错误。
内容的提问来源于stack exchange,提问作者Syed Iqbal Ahmed
相关产品推荐
相关产品推荐

