get请求
1、带参数的get请求
@Test
public void testGet(){
//带参数的get请求
given().
when().
get("https://httpbin.org/get?name=xiaoming").
then().
log().body();
}
如有其它参数在name=xiaoming后加&符号,继续拼接
当参数较多时我们可以使用其它方法
我们可以添加查询参数:queryParam("key","value"),如有多个值在后边添加.queryParm("key","value")
@Test
public void testGe1(){
//带参数的get请求
//当参数较多时,我们可以添加查询参数:queryParam("key","value"),如有多个值在后边添加.queryParm("key","value")
given().
queryParam("key","value").queryParam("key","value").
when().
get("https://httpbin.org/get?").
then().
log().body();
}
返回值为
{
"args": {
"key": "value",
"name": "xiaoming"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/4.5.3 (Java/1.8.0_231)",
"X-Amzn-Trace-Id": "Root=1-60f"
},
"origin": "***.***.**.**",
"url": "https://httpbin.org/get?key=value&name=xiaoming"
2、带多个参数的get请求--Map
@Test
public void testGet2(){
//带多个参数的get请求,可以使用Map
Map<String,String> map=new HashMap<String, String>();
map.put("name", "小明");
map.put("age","28");
map.put("address","北京");
given().
queryParams(map).
when().
get("http://httpbin.org/get").
then().
log().all();
}
POST请求
1、发post请求-form表单参数
@Test
public void testPost(){
//发post请求-form表单参数
//解决乱码问题:form表单有中文的话,要加charset=utf-8到contentType中
given().
formParam("name","小明").
contentType("application/x-www-form-urlencoded;charset=utf-8").
when().
//此处添加请求方式(例如:get/post请求)
post("http://httpbin.org/post").
then().//此处为断言,结果
log().all();
2、发post请求-XML参数类型
@Test
public void testPost2(){
String xm="里边写XML文件内容";
given().
contentType("text/xml;charset=utf-8").
body(xm).
when().
post("http://httpbin.org/post").
then().
log().all();
}
3、发post请求-多参数表单
@Test
public void testPost3() {
//发post请求-多参数表单
given(). //可以参照postman中的Headers中的参数类型写
contentType("multipart/form-data;charset=utf-8").
multiPart(new File("此处填写上传文件路径")).
when().
post("http://httpbin.org/post").
then().
log().all();
}
4、发post请求-json参数类型
如何把json数据传到代码中?
可以先把字符串保存起来, 用变量来接收
@Test
public void testPost1(){
//发post请求-json参数类型
//解决乱码问题:form表单有中文的话,要加charset=utf-8到content-type中
//把json保存起来用字符串接收为jsonStr,把字符串放到body()中
String jsonStr="{\"键\":\"值\",\"键\":\"值\"}";
given().
//此处可添加请求头、请求参数、请求体等
contentType("application/x-www-form-urlencoded;charset=utf-8").
body(jsonStr).
when().
//此处添加请求方式(例如:get/post请求)
post("http://httpbin.org/post").
then().//此处为断言,结果
log().all();
}