1 // Copyright (c) 2023 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 ylong_http_client::async_impl::{Body, Client, Downloader, Request};
17 use ylong_http_client::{Certificate, HttpClientError, Redirect, TlsVersion};
18 
main()19 fn main() {
20     let rt = tokio::runtime::Builder::new_multi_thread()
21         .enable_all()
22         .build()
23         .expect("Tokio runtime build err.");
24     let mut v = vec![];
25     for _i in 0..3 {
26         let handle = rt.spawn(req());
27         v.push(handle);
28     }
29 
30     rt.block_on(async move {
31         for h in v {
32             let _ = h.await;
33         }
34     });
35 }
36 
req() -> Result<(), HttpClientError>37 async fn req() -> Result<(), HttpClientError> {
38     let v = "some certs".as_bytes();
39     let cert = Certificate::from_pem(v)?;
40 
41     // Creates a `async_impl::Client`
42     let client = Client::builder()
43         .redirect(Redirect::default())
44         .tls_built_in_root_certs(false) // not use root certs
45         .danger_accept_invalid_certs(true) // not verify certs
46         .max_tls_version(TlsVersion::TLS_1_2)
47         .min_tls_version(TlsVersion::TLS_1_2)
48         .add_root_certificate(cert)
49         .build()?;
50 
51     // Creates a `Request`.
52     let request = Request::builder()
53         .url("https://www.example.com")
54         .body(Body::empty())?;
55 
56     // Sends request and receives a `Response`.
57     let response = client.request(request).await?;
58 
59     println!("{}", response.status().as_u16());
60     println!("{}", response.headers());
61 
62     // Reads the body of `Response` by using `BodyReader`.
63     let _ = Downloader::console(response).download().await;
64     Ok(())
65 }
66