你应该通过
Connection: close
HTTP标头,以便服务器可以正确关闭连接。
请注意,Google将返回压缩内容,因此您将得到一个错误:
错误=流不包含有效的UTF-8
,甚至发送标头
Accept-Encoding: identity
。
主机更改为的测试
www.rust-lang.org
:
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::net::TcpStream;
fn main() {
if let Err(err) = connect() {
println!("err = {}", err);
}
}
fn connect() -> Result<()> {
let mut stream = TcpStream::connect("www.rust-lang.org:80")?;
let mut request_data = String::new();
request_data.push_str("GET / HTTP/1.0");
request_data.push_str("\r\n");
request_data.push_str("Host: www.rust-lang.org");
request_data.push_str("\r\n");
request_data.push_str("Connection: close"); // <== Here!
request_data.push_str("\r\n");
request_data.push_str("\r\n");
println!("request_data = {:?}", request_data);
let request = stream.write_all(request_data.as_bytes())?;
println!("request = {:?}", request);
let mut buf = String::new();
let result = stream.read_to_string(&mut buf)?;
println!("result = {}", result);
println!("buf = {}", buf);
Ok(())
}
将导致:
request_data = "GET / HTTP/1.0\r\nHost: www.rust-lang.org\r\nConnection: close\r\n\r\n"
request = ()
result = 554
buf = HTTP/1.1 301 Moved Permanently
Server: CloudFront
Date: Sun, 13 May 2018 04:46:00 GMT
Content-Type: text/html
Content-Length: 183
Connection: close
Location: https://www.rust-lang.org/
X-Cache: Redirect from cloudfront
Via: 1.1 17af5476e6187c3063f9ba7f797d342b.cloudfront.net (CloudFront)
X-Amz-Cf-Id: lzMymVQ6vTv27VxSU4J0MR6EmgPDCDqO8KFimo1kPvxmQxcKjT33jg==
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>CloudFront</center>
</body>
</html>