我有以下代码,但是当我启动应用程序时,它请求页面但没有得到答复。

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(())
}

最佳答案

您应该传递 Connection: close HTTP header ,以便服务器可以正确关闭连接。

请注意,Google 将返回压缩内容,因此您会收到错误消息: err = 流不包含有效的 UTF-8 ,甚至发送 header 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>

关于http - 为什么使用 vanilla Rust 的 HTTP GET 请求没有得到答复?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50312240/

10-10 12:37