對於JMeter中文亂碼分為兩部分:
1、請求(request):由於引用了csv文件當csv文件編碼與JMeter不統一可能造成服務器收到數據的中文亂碼
2、返回(response):由於服務器返回數據為UTF-8格式並且沒有charset標記造成JMter解析錯誤,或者服務器返回的是unicode編碼造成JMeter無法顯示
中文亂碼只是看着不爽對於性能測試沒有影響,但對於功能測試可能就看着費勁了~~~
一、請求(request)中文亂碼
對於請求中文亂碼只需指定相應字符集即可。我安裝的是 apache-jmeter-5.1.1 默認已經改過無需修改
1、打開 jmeter.properties 配置文件 vi jmeter.properties 2、找到 csvdataset.file.encoding_list,修改配置如下 csvdataset.file.encoding_list=UTF-8|UTF-16|ISO-8859-15|US-ASCII 3、保存退出
二、返回(response)中文亂碼
對於返回中文亂碼又分兩種:
1、返回UTF-8中文字符
2、返回unicode編碼信息
2.1返回UTF-8中文字符
如下圖返回的就是utf-8的中文字符顯示一堆花碼。
解決方法:
1、添加BeanShell PostProcessor
2、加入如下代碼
prev.setDataEncoding("UTF-8");
3、再次運行腳本,此時已經顯示中文了
另外一個解決方法,修改 jmeter.properties 配置文件
1、打開 jmeter.properties 配置文件 vi jmeter.properties 2、找到 sampleresult.default.encoding,將原來 #sampleresult.default.encoding=ISO-8859-1 改為 sampleresult.default.encoding=UTF-8 3、保存退出
重新啟動JMeter再次運行腳本同樣可以顯示中文。
但這樣修改以后如果你只測試一個項目或者你的項目返回的都是UTF-8字符則沒問題,如果你有gb2312字符集那么那個項目又會出現亂碼。
2.2返回unicode編碼信息
如下圖返回 \uxxxx 就是unicode編碼內容,這樣在 BeanShell PostProcessor 中加入 prev.setDataEncoding("UTF-8"); 並無任何卵用,因為本身顯示的就是英文字符所以無用。
解決方法:
1、添加BeanShell PostProcessor 同上
2、加入如下代碼
prev.setDataEncoding("UTF-8"); String s=new String(prev.getResponseData(),"UTF-8"); char aChar; int len= s.length(); StringBuffer outBuffer=new StringBuffer(len); for(int x =0; x <len;){ aChar= s.charAt(x++); if(aChar=='\\'){ aChar= s.charAt(x++); if(aChar=='u'){ int value =0; for(int i=0;i<4;i++){ aChar= s.charAt(x++); switch(aChar){ case'0': case'1': case'2': case'3': case'4': case'5': case'6': case'7': case'8': case'9': value=(value <<4)+aChar-'0'; break; case'a': case'b': case'c': case'd': case'e': case'f': value=(value <<4)+10+aChar-'a'; break; case'A': case'B': case'C': case'D': case'E': case'F': value=(value <<4)+10+aChar-'A'; break; default: throw new IllegalArgumentException( "Malformed \\uxxxx encoding.");}} outBuffer.append((char) value);}else{ if(aChar=='t') aChar='\t'; else if(aChar=='r') aChar='\r'; else if(aChar=='n') aChar='\n'; else if(aChar=='f') aChar='\f'; outBuffer.append(aChar);}}else outBuffer.append(aChar);} prev.setResponseData(outBuffer.toString());
3、再次運行腳本,此時已經顯示中文了
注意:最前面這句 prev.setDataEncoding("UTF-8"); 還是要加。不然會顯示如下內容,雖然已將unicode轉回但由於字符集錯誤還是顯示亂碼
參考文檔: