python - 使用 OpenSSL 发送下载页面 - Python

标签 python sockets ssl get connection

我正在使用 pyOpenSSL 库建立连接。 以下是我创建连接的方式:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
self.context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD)
self.connection = OpenSSL.SSL.Connection(context, s)
self.connection.connect((url, SSL_PORT))

非常简单。现在我想向一个 url 发送一个 GET 请求,并下载它的页面:

def send(self, url):
    if not self.connection:
        log.warning("Connection not stablished")
        return None
    else:
        request = "GET / HTTP/1.1 Host: www.google.com"
        self.connection.send(request)
        log.info("Server response")
        log.info("-" * 40)
        resp = self.connection.recv(4096)
        while (len(resp) > 0):
            log.info(resp)
            resp = self.connection.recv(4096)
        return resp

但是我收到了 HTTP/1.1 408 REQUEST_TIMEOUT:

  File "./scurl", line 125, in send
    log.info(resp)
  File "/usr/local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 1320, in recv
    self._raise_ssl_error(self._ssl, result)
  File "/usr/local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 1167, in _raise_ssl_error
    raise ZeroReturnError()
OpenSSL.SSL.ZeroReturnError

下载页面内容的正确方法是什么?

***规则: **** 我不能使用其他图书馆。是的,这是为了家庭作业。我只是在处理 request 时遇到了问题。有人可以给我线索吗?

最佳答案

一方面,HTTP GET 请求看起来无效。应该是:

GET / HTTP/1.1\r\n
Host: www.google.com\r\n\r\n

Note the carriage return ('\r') and new line ('\n') characters at the end of each line. You can store this as a string like this:

request = "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n"

由于请求未正确终止,远程服务器将等待请求的其余部分,并最终以 HTTP 408 响应超时。


另一个问题可能是您可能正在从不同的连接读取数据。您使用实例成员 self.connection 发送:

self.connection.send(request)

但尝试阅读似乎是全局变量的响应:

resp = connection.recv(4096)

关于python - 使用 OpenSSL 发送下载页面 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665501/

相关文章:

Python数据库插入MySQL

python - 如何在 Python 中创建单个 webdriver 实例?

c++ - 读取整个文件并通过套接字发送

flash - 延长/续订 p12 自签名证书已过期

ssl - AWS 和 SSL 以及修改 EC2 实例的选项

python - 组合 for 和 if 循环

python - Python 3 中的随机盐字符串

php - 总是 `Could not bind to tcp://my_ip_here:8080 Address already in use`

c++ - 从 stdin 读取输入并准备好接收来自服务器的广播

.htaccess - 如何在没有重定向循环的情况下使用 htaccess 转发到 https