1use std::collections::HashMap;
2use std::str::FromStr;
3
4
5pub struct HttpUtil;
7
8impl HttpUtil {
9
10 pub async fn get(url: &str) -> Result<String, Box<dyn std::error::Error>> {
12 let result = reqwest::get(url)
13 .await?
14 .text()
15 .await?;
16 Ok(result)
17 }
18
19 pub fn blocking_get(url: &str) -> Result<String, Box<dyn std::error::Error>>{
21 let response = reqwest::blocking::get(url)?;
22 let result = response.text()?;
23 Ok(result)
24 }
25
26 pub async fn post(url: &str, body: String) -> Result<String, Box<dyn std::error::Error>> {
28 let client = reqwest::Client::new();
29 let result = client.post(url)
30 .body(body)
31 .send()
32 .await?
33 .text()
34 .await?;
35 Ok(result)
36 }
37
38 pub fn blocking_post(url: &str, body: String) -> Result<String, Box<dyn std::error::Error>> {
40 let client = reqwest::blocking::Client::new();
41 let result = client.post(url)
42 .body(body)
43 .send()?
44 .text()?;
45 Ok(result)
46 }
47
48 pub async fn post_json(url: &str, body: HashMap<&str, &str>) -> Result<String, Box<dyn std::error::Error>> {
49 let client = reqwest::Client::new();
50 let result = client.post(url)
51 .json(&body)
52 .send()
53 .await?
54 .text()
55 .await?;
56 Ok(result)
57 }
58
59 pub async fn post_form(url: &str, form: Vec<(&str, &str)>) -> Result<String, Box<dyn std::error::Error>> {
60 let client = reqwest::Client::new();
61 let result = client.post(url)
62 .form(&form)
63 .send()
64 .await?
65 .text()
66 .await?;
67 Ok(result)
68 }
69
70 pub async fn request(method: reqwest::Method, url: &str, headers: Vec<(&str, &str)>, body: &str) -> Result<String, Box<dyn std::error::Error>> {
71 let client = reqwest::Client::new();
72 let headers = headers.iter()
73 .map(|(k, v)| (reqwest::header::HeaderName::from_str(k).unwrap() , reqwest::header::HeaderValue::from_str(v).unwrap()))
74 .collect::<reqwest::header::HeaderMap>();
75 let result = client.request(method, url)
76 .headers(headers)
77 .body(body.to_string())
78 .send()
79 .await?
80 .text()
81 .await?;
82 Ok(result)
83 }
84
85 pub async fn post_bytes(url: &str, data: Vec<u8>) -> Result<(), Box<dyn std::error::Error>>{
86 let client = reqwest::Client::new();
87 let res = client.put(url)
88 .header("Content-Type", "image/jpeg")
89 .header("Content-Length", data.len())
90 .body(data)
91 .send()
92 .await;
93
94 let res = match res {
95 Ok(response) => response,
96 Err(e) => {
97 return Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, e)));
98 },
99 };
100 let status = res.status();
101 println!("status = {}, {}", status, res.text_with_charset("utf-8").await?);
102 Ok(())
103 }
104
105}