为什么使用rustls的TLS连接不返回响应?

问题描述 投票:-1回答:1

我正在使用How do I make a TLS connection using the rustls library?中的代码制作一个带TLS的套接字,并向Google发送GET请求。

当我运行cargo run时,程序不会在屏幕上打印任何内容。

use rustls;
use rustls::{ClientConfig, ClientSession, Session, TLSError};
use std::env;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::process;
use std::str;
use std::sync::Arc;
use webpki;
use webpki_roots;

fn main() {
    let mut socket = std::net::TcpStream::connect("www.google.com:443").unwrap();
    let mut config = rustls::ClientConfig::new();
    config
        .root_store
        .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
    let arc = std::sync::Arc::new(config);
    let dns_name = webpki::DNSNameRef::try_from_ascii_str("www.google.com").unwrap();
    let mut client = rustls::ClientSession::new(&arc, dns_name);
    let mut stream = rustls::Stream::new(&mut client, &mut socket); // Create stream
                                                                    // Instead of writing to the client, you write to the stream
    stream
        .write(b"GET / HTTP/1.1\r\nConnection: close\r\n\r\n")
        .unwrap();
    let mut plaintext = Vec::new();
    stream.read_to_end(&mut plaintext).unwrap();
    io::stdout().write_all(&plaintext).unwrap();
}

并且在我的Cargo.toml文件中:

[package]
name = "X"
version = "0.1.0"
authors = ["Behdad"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rustls = "0.17.0"
webpki = "0.21.2"
webpki-roots = "0.19.0"
serde_derive = "1.0.105"
serde = "1.0.105"
sockets ssl https rust
1个回答
2
投票
.write(b"GET / HTTP/1.1\r\nConnection: close\r\n\r\n")

这不是有效的HTTP / 1.1请求。它缺少Host标头。

© www.soinside.com 2019 - 2024. All rights reserved.