1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use crate::Exception;
use std::collections::HashMap;
use url::Url;
use urlencoding::{decode, encode};
/// URL utility class, for extracting parameters, URL encoding and decoding, etc.
pub struct UrlUtil;
impl UrlUtil {
/// 对URL进行编码处理
pub fn url_encode(url: &str) -> Result<String, Exception> {
let original_url = url;
// 解析原始 URL
let parsed_url = Url::parse(original_url)?;
Ok(parsed_url.to_string())
}
/// 从URL中提取查询参数并返回HashMap
pub fn parameters(url: &str) -> Result<HashMap<String, String>, Exception>{
let parsed_url = Url::parse(url)?;
let params: HashMap<String, String> = parsed_url.query_pairs()
.into_owned() // 将 &str 转换为 String(避免生命周期问题)
.collect();
Ok(params)
}
/// 对输入字符串进行URL编码处理
pub fn encode(str: &str) -> String {
encode(str).to_string()
}
/// 对输入字符串进行URL解码处理
pub fn decode(str: &str) -> String {
decode(str).unwrap().to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_url_encode() {
// TODO 测试未通过
let url = "https://www.baidu.com/s?wd=hello world";
let result = UrlUtil::url_encode(url).unwrap();
println!("{}", result);
assert_eq!(result, "https://www.baidu.com/s?wd=hello%20world");
}
#[test]
fn test_encode() {
let str = "hello world";
let result = UrlUtil::encode(str);
println!("{}", result);
}
}