我有以下代码,但它不会产生我期望的结果,我不明白原因。如果我启动应用程序它请求页面但没有得到答案。如果我能得到一个错误的提示,那将会很棒。
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.google.de:80")?;
let mut request_data = String::new();
request_data.push_str("GET / HTTP/1.1");
request_data.push_str("\r\n");
request_data.push_str("Host: www.google.de");
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(())
}
答案 0 :(得分:4)
您应该传递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>