2016-10-04 114 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);