rquest 5.1.0

A blazing-fast Rust HTTP Client with TLS fingerprint
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
#![allow(missing_debug_implementations)]

use super::NetworkScheme;
use crate::error::BoxError;
use http::{
    Error, HeaderMap, HeaderName, HeaderValue, Method, Request, Uri, Version,
    header::CONTENT_LENGTH, request::Builder,
};
use http_body::Body;
use std::{any::Any, marker::PhantomData};

/// Represents an HTTP request with additional metadata.
///
/// The `InnerRequest` struct encapsulates an HTTP request along with additional
/// metadata such as the HTTP version and network scheme. It provides methods
/// to build and manipulate the request.
///
/// # Type Parameters
///
/// - `B`: The body type of the request, which must implement the `Body` trait.
pub struct InnerRequest<B>
where
    B: Body + Send + Unpin + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
{
    request: Request<B>,
    version: Option<Version>,
    network_scheme: NetworkScheme,
}

impl<B> InnerRequest<B>
where
    B: Body + Send + Unpin + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
{
    /// Creates a new `InnerRequestBuilder`.
    ///
    /// This method returns a builder that can be used to construct an `InnerRequest`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rquest::util::client::request::InnerRequest;
    /// use http::Method;
    ///
    /// let request = InnerRequest::builder()
    ///     .method(Method::GET)
    ///     .uri("http://example.com".parse().unwrap())
    ///     .body(())
    ///     .unwrap();
    /// ```
    pub fn builder<'a>() -> InnerRequestBuilder<'a, B> {
        InnerRequestBuilder {
            builder: Request::builder(),
            version: None,
            network_scheme: Default::default(),
            headers_order: None,
            _body: PhantomData,
        }
    }

    /// Decomposes the `InnerRequest` into its components.
    ///
    /// This method returns a tuple containing the request, network scheme, and HTTP version.
    ///
    /// # Returns
    ///
    /// A tuple `(Request<B>, NetworkScheme, Option<Version>)` containing the components of the request.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rquest::util::client::request::InnerRequest;
    /// use http::Method;
    ///
    /// let request = InnerRequest::builder()
    ///     .method(Method::GET)
    ///     .uri("http://example.com".parse().unwrap())
    ///     .body(())
    ///     .unwrap();
    ///
    /// let (req, network_scheme, version) = request.pieces();
    /// ```
    pub fn pieces(self) -> (Request<B>, Option<Version>, NetworkScheme) {
        (self.request, self.version, self.network_scheme)
    }
}

/// A builder for constructing HTTP requests.
///
/// The `InnerRequestBuilder` struct provides a fluent interface for building
/// `InnerRequest` instances. It allows setting various properties of the request,
/// such as the method, URI, headers, and body.
///
/// # Type Parameters
///
/// - `B`: The body type of the request, which must implement the `Body` trait.
pub struct InnerRequestBuilder<'a, B>
where
    B: Body + Send + Unpin + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
{
    builder: Builder,
    version: Option<Version>,
    network_scheme: NetworkScheme,
    headers_order: Option<&'a [HeaderName]>,
    _body: PhantomData<B>,
}

impl<'a, B> InnerRequestBuilder<'a, B>
where
    B: Body + Send + Unpin + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
{
    /// Sets the method for the request.
    ///
    /// # Arguments
    ///
    /// * `method` - The HTTP method to be used for the request.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn method(mut self, method: Method) -> Self {
        self.builder = self.builder.method(method);
        self
    }

    /// Sets the URI for the request.
    ///
    /// # Arguments
    ///
    /// * `uri` - The URI to be used for the request.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn uri(mut self, uri: Uri) -> Self {
        self.builder = self.builder.uri(uri);
        self
    }

    /// Sets the version for the request.
    ///
    /// # Arguments
    ///
    /// * `version` - The HTTP version to be used for the request.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn version(mut self, version: Option<Version>) -> Self {
        if let Some(version) = version {
            self.builder = self.builder.version(version);
            // `Request` defaults to HTTP/1.1 as the version.
            // We don't know if the user has specified a version,
            // so we need to record it here for TLS ALPN negotiation.
            self.version = Some(version);
        }
        self
    }

    /// Sets the headers for the request.
    ///
    /// # Arguments
    ///
    /// * `headers` - The headers to be used for the request.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn headers(mut self, mut headers: HeaderMap) -> Self {
        if let Some(h) = self.builder.headers_mut() {
            std::mem::swap(h, &mut headers)
        }
        self
    }

    /// Sets the headers order for the request.
    ///
    /// # Arguments
    ///
    /// * `order` - The order in which headers should be sent.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn headers_order(mut self, order: Option<&'a [HeaderName]>) -> Self {
        self.headers_order = order;
        self
    }

    /// Sets an extension for the request.
    ///
    /// # Arguments
    ///
    /// * `extension` - The extension to be added to the request.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn extension<T>(mut self, extension: Option<T>) -> Self
    where
        T: Clone + Any + Send + Sync + 'static,
    {
        if let Some(extension) = extension {
            self.builder = self.builder.extension(extension);
        }
        self
    }

    /// Sets the network scheme for the request.
    ///
    /// # Arguments
    ///
    /// * `network_scheme` - The network scheme to be used for the request.
    ///
    /// # Returns
    ///
    /// The updated `InnerRequestBuilder`.
    #[inline]
    pub fn network_scheme(mut self, network_scheme: NetworkScheme) -> Self {
        self.network_scheme = network_scheme;
        self
    }

    /// Sets the body for the request.
    ///
    /// # Arguments
    ///
    /// * `body` - The body to be used for the request.
    ///
    /// # Returns
    ///
    /// A `Result` containing the constructed `InnerRequest` or an `Error`.
    #[inline]
    pub fn body(mut self, body: B) -> Result<InnerRequest<B>, Error> {
        if let Some((method, (headers, headers_order))) = self
            .builder
            .method_ref()
            .cloned()
            .zip(self.builder.headers_mut().zip(self.headers_order))
        {
            add_content_length_header(method, headers, &body);
            sort_headers(headers, headers_order);
        }

        self.builder.body(body).map(|request| InnerRequest {
            request,
            version: self.version,
            network_scheme: self.network_scheme,
        })
    }
}

/// Adds the `Content-Length` header to the request.
///
/// # Arguments
///
/// * `method` - The HTTP method of the request.
/// * `headers` - The headers of the request.
/// * `body` - The body of the request.
#[inline]
fn add_content_length_header<B>(method: Method, headers: &mut HeaderMap, body: &B)
where
    B: Body,
{
    if let Some(len) = Body::size_hint(body).exact() {
        if len != 0 || method_has_defined_payload_semantics(method) {
            headers
                .entry(CONTENT_LENGTH)
                .or_insert_with(|| HeaderValue::from(len));
        }
    }
}

/// Checks if the method has defined payload semantics.
///
/// # Arguments
///
/// * `method` - The HTTP method to check.
///
/// # Returns
///
/// `true` if the method has defined payload semantics, otherwise `false`.
#[inline]
fn method_has_defined_payload_semantics(method: Method) -> bool {
    !matches!(
        method,
        Method::GET | Method::HEAD | Method::DELETE | Method::CONNECT
    )
}

/// Sorts the headers in the specified order.
///
/// Headers in `headers_order` are sorted to the front, preserving their order.
/// Remaining headers are appended in their original order.
///
/// # Arguments
///
/// * `headers` - The headers to be sorted.
/// * `headers_order` - The order in which headers should be sent.
#[inline]
fn sort_headers(headers: &mut HeaderMap, headers_order: &[HeaderName]) {
    if headers.len() <= 1 {
        return;
    }

    // Create a new header map to store the sorted headers
    let mut sorted_headers = HeaderMap::with_capacity(headers.keys_len());

    // First insert headers in the specified order
    for name in headers_order {
        for value in headers.get_all(name) {
            sorted_headers.append(name.clone(), value.clone());
        }
        headers.remove(name);
    }

    // Then insert any remaining headers that were not ordered
    for (key, value) in headers.drain() {
        if let Some(key) = key {
            sorted_headers.append(key, value);
        }
    }

    std::mem::swap(headers, &mut sorted_headers);
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::{HeaderMap, HeaderName, HeaderValue};

    #[test]
    fn test_sort_headers() {
        let mut headers = HeaderMap::new();
        headers.insert("b-header", HeaderValue::from_static("b"));
        headers.insert("a-header", HeaderValue::from_static("a"));
        headers.insert("c-header", HeaderValue::from_static("c"));
        headers.insert("extra-header", HeaderValue::from_static("extra"));

        let headers_order = [
            HeaderName::from_static("a-header"),
            HeaderName::from_static("b-header"),
            HeaderName::from_static("c-header"),
        ];

        sort_headers(&mut headers, &headers_order);

        let mut iter = headers.iter();

        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("a-header"),
                &HeaderValue::from_static("a")
            ))
        );
        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("b-header"),
                &HeaderValue::from_static("b")
            ))
        );
        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("c-header"),
                &HeaderValue::from_static("c")
            ))
        );
        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("extra-header"),
                &HeaderValue::from_static("extra")
            ))
        );
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn test_sort_headers_partial_match() {
        let mut headers = HeaderMap::new();
        headers.insert("x-header", HeaderValue::from_static("x"));
        headers.insert("y-header", HeaderValue::from_static("y"));

        let headers_order = [
            HeaderName::from_static("y-header"),
            HeaderName::from_static("z-header"),
        ];

        sort_headers(&mut headers, &headers_order);

        let mut iter = headers.iter();

        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("y-header"),
                &HeaderValue::from_static("y")
            ))
        );
        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("x-header"),
                &HeaderValue::from_static("x")
            ))
        );
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn test_sort_headers_empty() {
        let mut headers = HeaderMap::new();
        let headers_order: [HeaderName; 0] = [];

        sort_headers(&mut headers, &headers_order);

        assert!(headers.is_empty());
    }

    #[test]
    fn test_sort_headers_no_ordering() {
        let mut headers = HeaderMap::new();
        headers.insert("random-header", HeaderValue::from_static("random"));

        let headers_order: [HeaderName; 0] = [];

        sort_headers(&mut headers, &headers_order);

        let mut iter = headers.iter();
        assert_eq!(
            iter.next(),
            Some((
                &HeaderName::from_static("random-header"),
                &HeaderValue::from_static("random")
            ))
        );
        assert_eq!(iter.next(), None);
    }
}