1 // Copyright (c) 2024 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //! This is a simple asynchronous HTTPS client example.
15
16 use std::io::Read;
17 use std::sync::Arc;
18
19 use ylong_http_client::async_impl::{Body, Client, ClientBuilder, Downloader, Request};
20 use ylong_http_client::{CertVerifier, HttpClientError, ServerCerts};
21
22 struct Verifier;
23
24 impl CertVerifier for Verifier {
verify(&self, certs: &ServerCerts) -> bool25 fn verify(&self, certs: &ServerCerts) -> bool {
26 // get version
27 let _ = certs.version().unwrap();
28 // get issuer
29 let _ = certs.issuer().unwrap();
30 // get name
31 let _ = certs.cert_name().unwrap();
32 // cmp cert file
33 let mut file = std::fs::File::open("./tests/file/cert.pem").unwrap();
34 let mut contents = String::new();
35 file.read_to_string(&mut contents).unwrap();
36 let _ = certs.cmp_pem_cert(contents.as_bytes()).unwrap();
37 println!("Custom Verified");
38 false
39 }
40 }
41
main() -> Result<(), HttpClientError>42 fn main() -> Result<(), HttpClientError> {
43 let mut handles = Vec::new();
44
45 let client = Arc::new(
46 ClientBuilder::new()
47 .cert_verifier(Verifier)
48 .build()
49 .unwrap(),
50 );
51
52 for _ in 0..4 {
53 let temp = client.clone();
54 handles.push(ylong_runtime::spawn(request(temp)));
55 }
56 for handle in handles {
57 let _ = ylong_runtime::block_on(handle);
58 }
59 Ok(())
60 }
61
request(client: Arc<Client>) -> Result<(), HttpClientError>62 async fn request(client: Arc<Client>) -> Result<(), HttpClientError> {
63 let request = Request::builder()
64 .url("https://www.example.com")
65 .body(Body::empty())
66 .unwrap();
67 // Sends request and receives a `Response`.
68 let response = client.request(request).await?;
69 // Reads the body of `Response` by using `BodyReader`.
70 Downloader::console(response).download().await
71 }
72