技術(shù)分享 | 接口測(cè)試中如何使用Json 來進(jìn)行數(shù)據(jù)交互 ?
本文節(jié)選自霍格沃茲測(cè)試開發(fā)學(xué)社內(nèi)部教材
json 是一種輕量級(jí)的傳輸數(shù)據(jù)格式,用于數(shù)據(jù)交互。json 請(qǐng)求類型的請(qǐng)求頭中的?Content-Type
?對(duì)應(yīng)為?application/json
?。碰到這種類型的接口,使用 Java 的 REST Assured 或者 Python 的 Requests 均可解決。
實(shí)戰(zhàn)演示
在 Python 中,使用 json 關(guān)鍵字參數(shù)發(fā)送 json 請(qǐng)求并傳遞請(qǐng)求體信息。
>>> import requests
>>> r = requests.post(
? ?'https://httpbin.ceshiren.com/post',
? ?json = {'key':'value'})
>>> r.request.headers
{'User-Agent': 'python-requests/2.22.0',
'Accept-Encoding': 'gzip, deflate',\
?'Accept': '*/*', 'Connection': 'keep-alive',
?'Content-Length': '16',\
? 'Content-Type': 'application/json'}
如果請(qǐng)求的參數(shù)選擇是json
?,那么Content-Type
?自動(dòng)變?yōu)?code>application/json?。
在 Java 中,使用contentType()方法添加請(qǐng)求頭信息,使用body()方法添加請(qǐng)求體信息。
import static org.hamcrest.core.IsEqual.equalTo;
import static io.restassured.RestAssured.*;
public class Requests {
? ? public static void main(String[] args) {
? ? ? ? String jsonData = "{\"key\": \"value\"}";
? ? ? ? //定義請(qǐng)求頭信息的contentType為application/json
? ? ? ? given().contentType("application/json").
? ? ? ? ? ? ? ? body(jsonData).
? ? ? ? ? ? ? ? when().
? ? ? ? ? ? ? ? post("https://httpbin.ceshiren.com/post").
? ? ? ? ? ? ? ? then().body("json.key", equalTo("value")).log().all();
? ? }
}