之前寫過一些關於復制瀏覽器中的請求做性能測試的文章:
基本思路是復制瀏覽器請求為curl
命令行,然后解析命令行組裝成HttpRequestBase
對象,然后結合FunTester
性能測試框架進行測試。
這次反過來,我寫了一個將HttpRequestBase
對象轉成curl
命令行形式的方法,用於在不同服務器上迅速重試請求,還可以通過一些參數的控制,了解HTTP
請求過程的時間消耗情況。
思路如下:1、將HttpRequestBase
對象轉成funrequest
對象;2、然后將funrequest
對象的屬性拼接成curl
命令。
步驟一
/**
* 從requestbase對象從初始化funrequest
* @param base
* @return
*/
static FunRequest initFromRequest(HttpRequestBase base) {
FunRequest request = null
String method = base.getMethod()
RequestType requestType = RequestType.getRequestType(method)
String uri = base.getURI().toString()
List<Header> headers = Arrays.asList(base.getAllHeaders())
if (requestType == requestType.GET) {
request = isGet().setUri(uri).addHeaders(headers)
} else if (requestType == RequestType.POST) {
HttpPost post = (HttpPost) base
HttpEntity entity = post.getEntity()
String value = entity.getContentType().getValue()
String content = null
try {
content = EntityUtils.toString(entity)
} catch (IOException e) {
logger.error("解析響應失敗!", e)
fail()
}
if (value.equalsIgnoreCase(HttpClientConstant.ContentType_TEXT.getValue()) || value.equalsIgnoreCase(HttpClientConstant.ContentType_JSON.getValue())) {
request = isPost().setUri(uri).addHeaders(headers).addJson(JSONObject.parseObject(content))
} else if (value.equalsIgnoreCase(HttpClientConstant.ContentType_FORM.getValue())) {
request = isPost().setUri(uri).addHeaders(headers).addParams(getJson(content.split("&")))
}
} else {
RequestException.fail("不支持的請求類型!")
}
return request
}
步驟二
/**
* 將請求對象轉成curl命令行
* @return
*/
String toCurl() {
StringBuffer curl = new StringBuffer("curl -w HTTPcode%{http_code}:代理返回code%{http_connect}:數據類型%{content_type}:DNS解析時間%{time_namelookup}:%{time_redirect}:連接建立完成時間%{time_pretransfer}:連接時間%{time_connect}:開始傳輸時間%{time_starttransfer}:總時間%{time_total}:下載速度%{speed_download}:speed_upload%{speed_upload} ")
if (requestType == RequestType.GET) curl << " -G"
headers.each {
curl << " -H '${it.getName()}:${it.getValue().replace(SPACE_1,EMPTY)}'"
}
switch (requestType) {
case RequestType.GET:
args.each {
curl << " -d '${it.key}=${it.value}'"
}
break
case RequestType.POST:
if (!params.isEmpty()) {
curl << " -H Content-Type:application/x-www-form-urlencoded"
params.each {
curl << " -F '${it.key}=${it.value}'"
}
}
if (!json.isEmpty()) {
curl << " -H \"Content-Type:application/json\"" //此處多余,防止從外部構建curl命令
json.each {
curl << " -d '${it.key}=${it.value}'"
}
}
break
default:
break
}
curl << " ${uri}"
// curl << " --compressed" //這里防止生成多個curl請求,批量生成有用
curl.toString()
}
測試服務代碼
這是用moco API
封裝過的框架的一部分。
public static void main(String[] args) {
def server = getServer(getLogMonitor("1.log"))
server.get(urlOnly("/test")).response(obRes(Result.success(getJson("324324=32432"))))
server.post(and(urlOnly("/post"),eqForm("a","a"))).response(textRes("234"))
server.response(MocoResponse.textRes("hello word"))
def run = run(server)
waitForKey("fan")
run.stop()
}
測試結果
控制台輸出的curl
命令行:curl -w HTTPcode%{http_code}:代理返回code%{http_connect}:數據類型%{content_type}:DNS解析時間%{time_namelookup}:%{time_redirect}:連接建立完成時間%{time_pretransfer}:連接時間%{time_connect}:開始傳輸時間%{time_starttransfer}:總時間%{time_total}:下載速度%{speed_download}:speed_upload%{speed_upload} -H 'Content-Type:application/x-www-form-urlencoded;charset=UTF-8' -H 'X-Requested-With:XMLHttpRequest' -H 'User-Agent:Mozilla/5.0(Macintosh;IntelMacOSX10_14_4)AppleWebKit/537.36(KHTML,likeGecko)Chrome/74.0.3729.108Safari/537.36' -H 'Connection:keep-alive' -H Content-Type:application/x-www-form-urlencoded -F 'a=a' http://localhost:12345/post
響應結果234
。