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