2016-10-04 117 views
0

我正在介绍JMeter纯Java,如何在httpSampler中设置content-type application/jsonJMeter API集内容类型

// HTTP Sampler 
 
     HTTPSampler httpSampler = new HTTPSampler(); 
 
     httpSampler.setDomain("localhost"); 
 
     httpSampler.setPort(8080); 
 
\t \t httpSampler.setPath("/posts"); 
 
     httpSampler.setMethod("POST"); 
 
     httpSampler.setName("API"); 
 

 
\t \t String data = "{\"items\":[{\"stacking_limit\":null,\"id\":\"MLA60428354\",\"weight\":300,\"height\":20,\"only_rotate_axis\":null,\"width\":35,\"length\":45,\"quantity\":1}],\"pack\":{\"weight\":2000,\"height\":100,\"width\":100,\"length\":100}}"; 
 
\t \t httpSampler.addNonEncodedArgument("", data, ""); 
 
\t \t httpSampler.setPostBodyRaw(true); 
 

 
\t \t HeaderManager headerManager = new HeaderManager(); 
 
\t \t Header h = new Header("Content-Type", "application/json"); 
 
\t \t headerManager.add(h); 
 
\t \t httpSampler.setHeaderManager(headerManager);

当我发个帖子到服务器,我检查头包含application/x-www-form-urlencoded,怎么改?

+0

您的代码看起来不错。你是如何检查包含“application/x-www-form-urlencoded”的头文件的?即你确定它是你的请求到达的“内容类型”,而不是响应的“接受”或“内容类型”?它也从JMeter UI工作(可能是你的服务器做一些奇怪的事情) –

回答

0

类似的问题已经被问在Five Ways To Launch a JMeter Test without Using the JMeter GUI文章的讨论,这里是解决方案的重要组成部分:

// Create Header Manager 
HeaderManager manager = new HeaderManager(); 
manager.add(new Header("Content-Type", "application/json")); 
manager.setName(JMeterUtils.getResString("header_manager_title")); 
manager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName()); 
manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName()); 

// Create HTTP Sampler 
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy(); 
httpSampler.setDomain("localhost"); 
httpSampler.setPort(8080); 
httpSampler.setPath("/posts"); 
httpSampler.setMethod("POST"); 
httpSampler.setName("API"); 
httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName()); 
httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName()); 

//Add HTTP Header Manager to HTTP Sampler  
HashTree httpSamplerTree = new HashTree(); 
httpSamplerTree.add(httpSampler, manager);