Rust与Postman交互的实例
使用Rust与Postman交互的实例,涵盖HTTP请求、API测试及自动化场景。内容按功能分类,代码示例基于reqwest
库(Rust的HTTP客户端),并标注关键配置。
基础GET请求
发送GET请求并打印响应
use reqwest;
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let response = reqwest::get("https://jsonplaceholder.typicode.com/posts/1")
.await?
.text()
.await?;
println!("{}", response);
Ok(())
}
带查询参数的GET
添加URL查询参数
let client = reqwest::Client::new();
let response = client.get("https://api.example.com/data")
.query(&[("key", "value"), ("page", "1")])
.send()
.await?;
自定义请求头
设置User-Agent
和Authorization
let response = client.get("https://api.example.com/protected")
.header("User-Agent", "Rust-Postman-Example")
.bearer_auth("your_token_here")
.send()
.await?;
POST JSON数据
发送JSON请求体
let data = serde_json::json!({"title": "foo", "body": "bar", "userId": 1});
let response = client.post("https://jsonplaceholder.typicode.com/posts")
.json(&data)
.send()
.await?;
表单数据提交
发送application/x-www-form-urlencoded
let params = [("username", "foo"), ("password", "bar")];
let response = client.post("https://api.example.com/login")
.form(¶ms)
.send()
.await?;
文件上传
通过多部分表单上传文件
let form = reqwest::multipart::Form::new()
.file("file", "path/to/file.txt")?;
let response = client.post("https://api.example.com/upload")
.multipart(form)
.send()
.await?;
处理响应JSON
解析JSON响应为结构体
#[derive(serde::Deserialize)]
struct Post {
id: i32,
title: String,
}
let post: Post = client.get("https://jsonplaceholder.typicode.com/posts/1")
.send()
.await?
.json()
.await?;
println!("Post title: {}", post.title);
错误处理
检查HTTP状态码
let response = client.get("https://api.example.com/endpoint").send().await?;
if response.status().is_success() {
println!("Success!");
} else {
println!("Failed: {}", response.status());
}
超时设置
配置请求超时时间
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()?;
异步并发请求
使用futures
并发多个请求
let requests = vec![
client.get("https://api.example.com/data1"),
client.get("https://api.example.com/data2"),
];
let responses = futures::future::join_all(requests).await;
代理配置
通过代理发送请求
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::https("http://proxy.example.com:8080")?)
.build()?;
Postman中的basic_auth
基础认证示例
Postman中的basic_auth
方法用于设置HTTP基本认证,以下为30个实例:
用户名和密码均为字符串
basic_auth("admin", Some("admin123"))
basic_auth("user1", Some("password1"))
basic_auth("test", Some("test@123"))
空密码或可选密码
basic_auth("guest", None) // 无密码
basic_auth("api_user", Some("")) // 空密码
basic_auth("temp", Some(null)) // 密码为null
特殊字符密码
basic_auth("dev", Some("p@$$w0rd!"))
basic_auth("root", Some("#Secure*123"))
basic_auth("service", Some("汉字密码"))
模拟测试场景
basic_auth("mock_user", Some("mock_pass"))
basic_auth("load_test", Some("test_credential"))
basic_auth("staging", Some("env@staging"))
OAuth2集成
basic_auth("client_id", Some("client_secret"))
basic_auth("oauth2_user", Some("token_123"))
basic_auth("auth_server", Some("server_key"))
数据库连接
basic_auth("db_admin", Some("mysql_pass"))
basic_auth("mongo_user", Some("mongo@321"))
basic_auth("redis", Some("redis_password"))
云服务认证
basic_auth("aws_key", Some("aws_secret"))
basic_auth("azure_user", Some("azure_key"))
basic_auth("gcp_service", Some("gcp_password"))
第三方API
basic_auth("twitter_api", Some("api_secret"))
basic_auth("stripe", Some("stripe_key"))
basic_auth("paypal", Some("paypal_token"))
企业系统
basic_auth("erp_admin", Some("erp@2023"))
basic_auth("crm_user", Some("crm_password"))
basic_auth("hr_system", Some("hr_access"))
安全测试用例
basic_auth("xss_test", Some("<script>alert(1)</script>"))
basic_auth("sql_inject", Some("' OR '1'='1"))
basic_auth("jwt_user", Some("eyJhbGciOi..."))
注意事项
Some()
用于包装密码参数,None
表示无密码- 实际密码应避免使用示例中的简单字符串
- 特殊字符密码需确保服务端兼容性
- 生产环境建议使用环境变量存储敏感凭证
代码格式化规范
所有代码示例均使用Markdown代码块包裹,语言标识为javascript:
```javascript
// 示例代码
Postman中使用client.cookie_store(true)
在Postman中使用client.cookie_store(true)
可以启用或管理Cookie存储功能。以下是20个实例,涵盖不同场景下的应用:
启用全局Cookie存储
pm.sendRequest({
url: 'https://example.com/login',
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: {
mode: 'raw',
raw: JSON.stringify({ username: 'user', password: 'pass' })
}
}, function (err, res) {
client.cookie_store(true); // 启用Cookie存储
console.log(res.cookies);
});
登录后保存会话
client.cookie_store(true);
pm.sendRequest({
url: 'https://api.example.com/session',
method: 'POST'
}, function (err, res) {
console.log('Session cookies:', res.cookies);
});
跨请求共享Cookie
client.cookie_store(true);
pm.sendRequest({
url: 'https://example.com/auth',
method: 'GET'
}, function (err, res) {
pm.sendRequest({
url: 'https://example.com/profile',
method: 'GET'
}, function (err, res) {
console.log(res.json());
});
});
禁用Cookie存储
client.cookie_store(false); // 显式禁用
pm.sendRequest({
url: 'https://example.com/no-cookies',
method: 'GET'
}, function (err, res) {
console.log(res.headers);
});
检查当前Cookie状态
const isEnabled = client.cookie_store(); // 返回布尔值
console.log(`Cookie storage is ${isEnabled ? 'enabled' : 'disabled'}`);
动态切换Cookie存储
client.cookie_store(true);
pm.sendRequest({ url: 'https://example.com/step1', method: 'GET' }, () => {
client.cookie_store(false);
pm.sendRequest({ url: 'https://example.com/step2', method: 'GET' }, () => {
console.log('Completed with mixed cookie settings');
});
});
清除特定域名的Cookie
client.cookie_store(true);
pm.sendRequest({
url: 'https://example.com/clear-cookies',
method: 'POST',
body: { mode: 'raw', raw: JSON.stringify({ action: 'clear' }) }
}, function (err, res) {
client.cookie_store.clear('example.com'); // 清除指定域名
});
导出当前Cookie
client.cookie_store(true);
const allCookies = client.cookie_store.all();
console.log('All stored cookies:', allCookies);
条件性Cookie存储
const shouldStoreCookies = pm.variables.get('store_cookies') === 'true';
client.cookie_store(shouldStoreCookies);
pm.sendRequest({ url: 'https://example.com', method: 'GET' });
测试环境配置
client.cookie_store(true);
pm.environment.set('cookie_enabled', 'true');
pm.sendRequest({
url: pm.environment.get('api_url') + '/test',
method: 'GET'
});
忽略SSL证书的Cookie存储
client.cookie_store(true);
pm.sendRequest({
url: 'https://insecure.example.com',
method: 'GET',
rejectUnauthorized: false // 忽略SSL错误
}, function (err, res) {
console.log(res.cookies);
});
定时清除Cookie
client.cookie_store(true);
setTimeout(() => {
client.cookie_store.clearAll();
console.log('Cookies cleared after 5 seconds');
}, 5000);
文件下载时保留Cookie
client.cookie_store(true);
pm.sendRequest({
url: 'https://example.com/download',
method: 'GET',
encoding: 'binary'
}, function (err, res) {
console.log('Download completed with cookies:', res.cookies);
});
多步骤认证流程
client.cookie_store(true);
// 步骤1:获取token
pm.sendRequest({ url: 'https://example.com/token', method: 'GET' }, () => {
// 步骤2:使用token认证
pm.sendRequest({ url: 'https://example.com/secure', method: 'GET' });
});
禁用重定向时的Cookie
client.cookie_store(true);
pm.sendRequest({
url: 'https://example.com/redirect',
method: 'GET',
followRedirects: false
}, function (err, res) {
console.log('Stopped redirect, cookies:', res.cookies);
});
自定义Cookie头
client.cookie_store(true);
pm.sendRequest({
url: 'https://example.com',
method: 'GET',
headers: { 'Custom-Header': 'value' }
}, function (err, res) {
console.log('Response with custom header:', res.json());
});
性能测试中的Cookie处理
client.cookie_store(true);
for (let i = 0; i < 10; i++) {
pm.sendRequest({ url: 'https://example.com/load-test', method: 'GET' });
}
检查Cookie过期时间
client.cookie_store(true);
pm.sendRequest({ url: 'https://example.com', method: 'GET' }, function (err, res) {
const cookies = res.cookies;
cookies.forEach(cookie => {
console.log(`${cookie.name} expires at ${cookie.expires}`);
});
});
模拟浏览器行为
client.cookie_store(true);
pm.sendRequest({
url: 'https://example.com',
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0'
}
});
错误处理示例
client.cookie_store(true);
pm.sendRequest({ url: 'https://invalid-url', method: 'GET' }, function (err) {
if (err) {
console.error('Request failed:', err.message);
client.cookie_store(false); // 出错时禁用
}
});
这些示例涵盖了从基础到高级的多种场景,可根据实际需求调整参数和逻辑。注意某些功能可能需要Postman的特定版本或插件支持。
基于Postman重定向
以下是基于Postman中.redirect(Policy::limited(5))
的实例,涵盖不同场景下的重定向策略使用:
重定向到同一域名下的不同路径
pm.sendRequest({
url: "https://example.com/login",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到HTTPS协议
pm.sendRequest({
url: "http://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到不同子域名
pm.sendRequest({
url: "https://old.example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到API版本更新
pm.sendRequest({
url: "https://api.example.com/v1",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到CDN资源
pm.sendRequest({
url: "https://example.com/assets/image.jpg",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到负载均衡节点
pm.sendRequest({
url: "https://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到维护页面
pm.sendRequest({
url: "https://example.com/service",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到地理定位页面
pm.sendRequest({
url: "https://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到认证服务
pm.sendRequest({
url: "https://example.com/secure",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到多语言页面
pm.sendRequest({
url: "https://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到短链接
pm.sendRequest({
url: "https://short.example.com/abc123",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到移动设备优化页面
pm.sendRequest({
url: "https://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到缓存资源
pm.sendRequest({
url: "https://example.com/static/js/main.js",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到第三方服务
pm.sendRequest({
url: "https://example.com/payment",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到错误页面
pm.sendRequest({
url: "https://example.com/404",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到内容分发网络
pm.sendRequest({
url: "https://example.com/video.mp4",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到A/B测试页面
pm.sendRequest({
url: "https://example.com/landing",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到API网关
pm.sendRequest({
url: "https://api.example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到镜像站点
pm.sendRequest({
url: "https://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
重定向到临时维护页面
pm.sendRequest({
url: "https://example.com",
method: "GET",
redirect: {
follow: true,
max: 5
}
}, (err, res) => {});
这些示例展示了不同场景下如何使用Postman的.redirect(Policy::limited(5))
功能处理重定向请求,限制重定向次数为5次。
使用Postman启用gzip压缩的实例
以下是在Postman中使用.gzip(true)
启用gzip压缩的20个实例,覆盖了不同类型的API请求场景。
基本的GET请求
pm.sendRequest({
url: 'https://api.example.com/data',
method: 'GET',
headers: {
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带查询参数的GET请求
pm.sendRequest({
url: 'https://api.example.com/data?param1=value1¶m2=value2',
method: 'GET',
headers: {
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
POST请求带JSON数据
pm.sendRequest({
url: 'https://api.example.com/data',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: JSON.stringify({ key: 'value' }),
options: {
gzip: true
}
}
});
POST请求带表单数据
pm.sendRequest({
url: 'https://api.example.com/form',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'name', value: 'John' },
{ key: 'age', value: '30' }
],
options: {
gzip: true
}
}
});
PUT请求更新资源
pm.sendRequest({
url: 'https://api.example.com/data/1',
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: JSON.stringify({ key: 'updatedValue' }),
options: {
gzip: true
}
}
});
DELETE请求
pm.sendRequest({
url: 'https://api.example.com/data/1',
method: 'DELETE',
headers: {
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带认证头的GET请求
pm.sendRequest({
url: 'https://api.example.com/protected',
method: 'GET',
headers: {
'Authorization': 'Bearer token123',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带自定义头的POST请求
pm.sendRequest({
url: 'https://api.example.com/custom',
method: 'POST',
headers: {
'X-Custom-Header': 'value',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: JSON.stringify({ data: 'value' }),
options: {
gzip: true
}
}
});
带分页的GET请求
pm.sendRequest({
url: 'https://api.example.com/data?page=1&limit=10',
method: 'GET',
headers: {
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带过滤条件的GET请求
pm.sendRequest({
url: 'https://api.example.com/data?status=active',
method: 'GET',
headers: {
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
上传文件的POST请求
pm.sendRequest({
url: 'https://api.example.com/upload',
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'formdata',
formdata: [
{ key: 'file', type: 'file', src: '/path/to/file.txt' }
],
options: {
gzip: true
}
}
});
带时间戳的GET请求
pm.sendRequest({
url: 'https://api.example.com/data?timestamp=' + new Date().getTime(),
method: 'GET',
headers: {
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带Cookies的GET请求
pm.sendRequest({
url: 'https://api.example.com/session',
method: 'GET',
headers: {
'Cookie': 'sessionId=abc123',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带User-Agent的GET请求
pm.sendRequest({
url: 'https://api.example.com/data',
method: 'GET',
headers: {
'User-Agent': 'PostmanRuntime/7.28.4',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带XML数据的POST请求
pm.sendRequest({
url: 'https://api.example.com/xml',
method: 'POST',
headers: {
'Content-Type': 'application/xml',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: '<root><key>value</key></root>',
options: {
gzip: true
}
}
});
带GraphQL查询的POST请求
pm.sendRequest({
url: 'https://api.example.com/graphql',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: JSON.stringify({ query: '{ user { name } }' }),
options: {
gzip: true
}
}
});
带OAuth2认证的GET请求
pm.sendRequest({
url: 'https://api.example.com/secure',
method: 'GET',
headers: {
'Authorization': 'Bearer oauth2_token',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
带多个头部的POST请求
pm.sendRequest({
url: 'https://api.example.com/multi',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Request-ID': '12345',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: JSON.stringify({ data: 'value' }),
options: {
gzip: true
}
}
});
带二进制数据的POST请求
pm.sendRequest({
url: 'https://api.example.com/binary',
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
raw: 'binary_data_here',
options: {
gzip: true
}
}
});
带条件头的GET请求
pm.sendRequest({
url: 'https://api.example.com/conditional',
method: 'GET',
headers: {
'If-None-Match': 'etag_value',
'Accept-Encoding': 'gzip'
},
body: {
mode: 'raw',
options: {
gzip: true
}
}
});
这些实例涵盖了多种常见的API请求场景,展示了如何在Postman中使用.gzip(true)
来启用gzip压缩。每个实例都包含了必要的头部和请求体配置,确保请求能够正确发送并