diff --git a/src/client.rs b/src/client.rs index ca57d8d3..526f0338 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1166,6 +1166,8 @@ impl crate::interceptor::Invoke for &HttpClient { mut request: Request, ) -> crate::interceptor::InterceptorFuture<'_, Error> { Box::pin(async move { + let is_head_request = request.method() == http::Method::HEAD; + // Set default user agent if not specified. request .headers_mut() @@ -1212,17 +1214,21 @@ impl crate::interceptor::Invoke for &HttpClient { // Convert the reader into an opaque Body. Ok(response.map(|reader| { - let body = ResponseBody { - inner: reader, - // Extend the lifetime of the agent by including a reference - // to its handle in the response body. - _client: (*self).clone(), - }; - - if let Some(len) = body_len { - AsyncBody::from_reader_sized(body, len) + if is_head_request { + AsyncBody::empty() } else { - AsyncBody::from_reader(body) + let body = ResponseBody { + inner: reader, + // Extend the lifetime of the agent by including a reference + // to its handle in the response body. + _client: (*self).clone(), + }; + + if let Some(len) = body_len { + AsyncBody::from_reader_sized(body, len) + } else { + AsyncBody::from_reader(body) + } } })) }) diff --git a/tests/response_body.rs b/tests/response_body.rs index 0655d67a..0bd428ef 100644 --- a/tests/response_body.rs +++ b/tests/response_body.rs @@ -18,6 +18,18 @@ fn simple_response_body() { assert_eq!(response_text, "hello world"); } +#[test] +fn zero_length_response_body() { + let m = mock! { + body: "", + }; + + let response = isahc::get(m.url()).unwrap(); + + assert_eq!(response.body().len(), Some(0)); + assert!(!response.body().is_empty()); +} + #[test] fn large_response_body() { let body = "wow so large ".repeat(1000); @@ -58,6 +70,20 @@ fn response_body_with_chunked_encoding_has_unknown_size() { assert_eq!(response.body().len(), None); } +// See issue #341. +#[test] +fn head_request_with_content_length_response_returns_empty_body() { + let m = mock! { + headers { + "content-length": 767, + } + }; + + let response = isahc::head(m.url()).unwrap(); + + assert!(response.body().is_empty()); +} + // See issue #64. #[test] fn dropping_client_does_not_abort_response_transfer() {