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 HTTP2 client example using the
15 //! ylong_http_client crate. It demonstrates creating a client, making a
16 //! request, and reading the response asynchronously.
17 #[cfg(feature = "tokio_base")]
18 use ylong_http_client::async_impl::{Body, ClientBuilder};
19 #[cfg(feature = "tokio_base")]
20 use ylong_http_client::{HttpClientError, RequestBuilder, StatusCode, TextBody, Version};
21
22 #[cfg(feature = "tokio_base")]
main() -> Result<(), HttpClientError>23 fn main() -> Result<(), HttpClientError> {
24 let rt = tokio::runtime::Builder::new_multi_thread()
25 .worker_threads(1)
26 .enable_all()
27 .build()?;
28
29 let client = ClientBuilder::new().http2_prior_knowledge().build()?;
30
31 let request = RequestBuilder::new()
32 .version("HTTP/2.0")
33 .url("127.0.0.1:5678")
34 .method("GET")
35 .header("host", "127.0.0.1")
36 .body(TextBody::from_bytes("Hi".as_bytes()))?;
37
38 rt.block_on(async move {
39 let mut response = client.request(request).await?;
40 assert_eq!(response.version(), &Version::HTTP2);
41 assert_eq!(response.status(), &StatusCode::OK);
42
43 let mut buf = [0u8; 4096];
44 let mut size = 0;
45
46 loop {
47 let read = response
48 .body_mut()
49 .data(&mut buf[size..])
50 .await
51 .expect("Response body read failed");
52 if read == 0 {
53 break;
54 }
55 size += read;
56 }
57 assert_eq!(
58 &buf[..size],
59 "hello world".as_bytes(),
60 "Assert response body failed"
61 );
62 });
63 Ok(())
64 }
65