將HTTP請求對象轉成curl命令行

之前寫過一些關於複製瀏覽器中的請求做性能測試的文章:

基本思路是複製瀏覽器請求爲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


FunTester騰訊雲社區欽定年度作者,非著名測試開發er,歡迎關注。

點擊閱讀原文,查看公衆號歷史文章
- END -


本文分享自微信公衆號 - FunTester(NuclearTester)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章