我正在编写验证我们的 JSONRPC 服务器的测试,并且我想使用requests 模块来测试设置无效的 Content-Length 和 Content-Type 标头等内容。但是,我们的服务器需要有效的客户端证书,而我不能让 requests 模块正确使用我的客户证书,如他们的 turorial 中所述。
如果我只是打开一个套接字并手动发送数据,它就可以正常工作:
>>> import socket, ssl
>>> s = """\
... POST /jsonrpc HTTP/1.1
... Host: example.com
... Content-Length: 77
...
... {"params": [{"example": "parameter"}], "id": 1, "method": "example.function"}\
... """.replace("\n", "\r\n")
>>> sock = socket.create_connection(("example.com", 443))
>>> sock = ssl.wrap_socket(sock, keyfile = "key.pem", certfile = "cert.pem")
>>> sock.sendall(s)
144
>>> print(sock.recv(4096) + sock.recv(4096))
HTTP/1.1 200 OK
Date: Mon, 23 Jul 2012 19:50:17 GMT
Server: CherryPy/3.2.0
Content-Length: 53
Content-Type: application/json
Set-Cookie: session_id=4ee3f4c435aee126c8042d4fba99962a48ca0a37; expires=Mon, 23 Jul 2012 20:20:17 GMT; Path=/; secure
Connection: close
{"jsonrpc": "2.0", "id": 1, "result": "Hello World!"}
但是当我使用 requests 模块做同样的事情时,它失败了:
>>> import requests
>>> data = '{"params": [{"example": "parameter"}], "id": 1, "method": "example.function"}'
>>> r = requests.post("https://example.com/jsonrpc", data = data, headers = {"Content-Length": "77"}, timeout = 2, verify = False, cert = ("cert.pem", "key.pem"))
>>> print r.content
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /jsonrpc
on this server.</p>
<hr>
<address>Apache/2.2.15 (Red Hat) Server at example.com Port 443</address>
</body></html>
所以我不仅不知道为什么会失败,我什至不知道如何找出问题所在。我可以尝试获得更改我们的 Apache 服务器设置以提高日志记录的权限,这可能会对此有所了解。但是客户端有什么方法可以找出失败的原因吗?