首页 > 技术文章 > postman发送不同格式的请求

xnancy 2021-06-02 16:46 原文

1.Post application/json格式请求

//定义post的参数
var paramdata = {
"_t":"1615453843355",
"password":"123456",
"platformType":"1",
"systemCode":"dcp-adm",
"username":"mzkj"
}
//const定义一个post请求常量
const loginRequest = {
    url: 'http://47.112.237.71:14444/user/login',   //请求的url
    method: 'POST',//请求的方法
    header: //请求头信息
    {'Content-Type':'application/json;charset=utf-8',
     'Accept': 'application/json;charset=utf-8'
    },
    body: //请求体信息,请求body中携带的参数
    {
        mode: 'raw',
        raw: JSON.stringify(paramdata)  //JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个JSON字符串
    }
};
 
//发送post请求
pm.sendRequest(loginRequest, function (err, res)
{
    if (res.json().data.token) {
    tests["Body has token"] = true;
//把得到的结果,设置环境变量token
    pm.environment.set("token",res.json().data.token);
}
else {
tests["Body has token"] = false;
}}
);
 
 

2.Post x-www-form-urlencoded格式请求

const loginRequest = {
    url: '127.0.0.1:8000/member/api/login/',
    method: 'POST',
    header: {
             'Content-Type':'application/x-www-form-urlencoded',
             'Accept': 'application/json'
            },
    body: {
        mode: 'urlencoded',            // 模式为表单url编码模式
        urlencoded:[{key:"user_name", value:"sunwk10005"},
                    {key:"password", value:"a1122334"}
        ],
    }
};
 
// 发送请求
pm.sendRequest(loginRequest, function (err, res)
{ console.log(err ? err : res.text()); });
 

3.get请求

const url = 'http://115.28.108.130:5000/api/user/getToken/?appid=136425';
// 发送get请求
pm.sendRequest(url, function (err, res) {
  console.log(err ? err : res.text());  // 控制台打印请求文本
});
//同样可以配合pm.environment.set(key:value)来将响应中的数据保存到环境变量中以供请求使用

4.XML格式请求

//构造请求
const demoRequest = {
  url: 'http://httpbin.org/post',
  method: 'POST',
  header: 'Content-Type: application/xml',  // 请求头种指定内容格式
  body: {
    mode: 'raw',
    raw: '<xml>hello</xml>'  // 按文本格式发送xml
  }
};

//发送请求
pm.sendRequest(demoRequest, function (err, res) {
  console.log(err ? err : res.json());
});

推荐阅读