nGrinder中快速編寫groovy腳本04-發送POST請求

POST請求分類:

1、根據是否修改代碼,分爲兩種方式:

一種是在UI界面添加後自動生成腳本,一種是直接在腳本中添加

2、根據請求參數的不同,主要可以分爲兩種:

param爲key value格式

body爲json格式

一、通過UI方式發送POST請求–key/value參數

通過 UI 設置:腳本 -> 新建腳本 -> 顯示高級配置

當選擇了請求方法爲POST後,在高級配置中默認會在headers中顯示Content-Type爲x-www-form-urlencoded,同時,添加key/value格式的params:


webp

生成代碼如下(由於篇幅限制,去掉import部分):

@RunWith(GrinderRunner)

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

class TestRunner {

public static GTest test

public static HTTPRequest request

public static NVPair[] headers = []

public static NVPair[] params = []

public static Cookie[] cookies = []

@BeforeProcess

public static void beforeProcess() {

HTTPPluginControl.getConnectionDefaults().timeout = 6000

test = new GTest(1, "www.baidu.com")

request = new HTTPRequest()

// Set header datas

List<NVPair> headerList = new ArrayList<NVPair>()

headerList.add(new NVPair("Content-Type", "application/x-www-form-urlencoded"))

headerList.add(new NVPair("Connection", "keep-alive"))

headers = headerList.toArray()

// Set param datas

List<NVPair> paramList = new ArrayList<NVPair>()

paramList.add(new NVPair("name", "jing"))

paramList.add(new NVPair("age", "18"))

paramList.add(new NVPair("desc", "beauty"))

params = paramList.toArray()

// Set cookie datas

List<Cookie> cookieList = new ArrayList<Cookie>()

cookieList.add(new Cookie("token", "xxxxxxxx", "www.baidu.com", "", new Date(32503647599000L), false))

cookies = cookieList.toArray()

grinder.logger.info("before process.");

}

@BeforeThread

public void beforeThread() {

test.record(this, "test")

grinder.statistics.delayReports=true;

grinder.logger.info("before thread.");

}

@Before

public void before() {

request.setHeaders(headers)

cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }

grinder.logger.info("before thread. init headers and cookies");

}

@Test

public void test(){

HTTPResponse result = request.POST("https://www.baidu.com", params)

assertThat(result.statusCode, is(200))

assertThat(result.getText(), containsString("jing"))

}

}

從以上代碼可以看出,這種方式跟之前使用GET方式添加參數的效果一樣,都是把參數添加在@BeforeProcess,不同的只是在@Test中使用的是request.POST方法。

二、通過UI方式發送POST請求–json

通過 UI 設置:腳本 -> 新建腳本 -> 顯示高級配置

當選擇了請求方法爲POST後,在高級配置中的headers中選擇Content-Type爲application/json,同時,添加json字符串:


webp

生成代碼如下(由於篇幅限制,去掉import部分):

@RunWith(GrinderRunner)

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

class TestRunner {

public static GTest test

public static HTTPRequest request

public static NVPair[] headers = []

public static String body = "{\"name\":\"jing\",\"comment\":\"hello\"}"

public static Cookie[] cookies = []

@BeforeProcess

public static void beforeProcess() {

HTTPPluginControl.getConnectionDefaults().timeout = 6000

test = new GTest(1, "www.baidu.com")

request = new HTTPRequest()

// Set header datas

List<NVPair> headerList = new ArrayList<NVPair>()

headerList.add(new NVPair("Content-Type", "application/json"))

headers = headerList.toArray()

grinder.logger.info("before process.");

}

@BeforeThread

public void beforeThread() {

test.record(this, "test")

grinder.statistics.delayReports=true;

grinder.logger.info("before thread.");

}

@Before

public void before() {

request.setHeaders(headers)

cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }

grinder.logger.info("before thread. init headers and cookies");

}

@Test

public void test(){

HTTPResponse result = request.POST("https://www.baidu.com", body.getBytes())

assertThat(result.statusCode, is(200))

}

}

從以上代碼可以看出,這種方式是在靜態變量中定義了body的內容,在@BeforeProcess中添加json請求頭,並在@Test中的request.POST方法中加入了body參數。

關鍵代碼如下:

public static String body = "{\"name\":\"jing\",\"comment\":\"hello\"}"

headerList.add(new NVPair("Content-Type", "application/json"))

HTTPResponse result = request.POST("https://www.baidu.com", body.getBytes())

三、直接在腳本中爲POST請求添加json格式的body

使用UI方式添加的json字符串默認是在創建靜態變量body的同時添加的;

直接修改腳本的話,就比較靈活,可以在類的任意位置添加,然後在POST請求中調用

(但是要注意變量作用域的問題)

// 定義json字符串

String jsonStr = '{"name": "jing"}';

//在@Test的POST方法中使用json字符串,同時添加header

request.POST("https://www.baidu.com", jsonStr.getBytes(), [

    new NVPair("Content-Type", "application/json"

] as NVPair[])

其中,需要注意的是:

POST(java.lang.String uri, byte[] data)

此方法中接收body參數時需要把字符串轉成字節數組。


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