我正在发送 HTTP
POST
请求使用 python
套接字:
import socket
s = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 4001))
s.send(b'POST /session HTTP/1.1\r\nContent-Type:application/json\r\nUser-Agent: test/1\r\n\r\n{"desiredCapabilities": {}, "capabilities":{}}')
response = s.recv(10000)
print(response)
输出:
b'HTTP/1.1 200 OK\r\ncontent-length: 270\r\nContent-Type: application/json; charset=utf-8\r\nConnection: close\r\n\r\n{"sessionId":"72418bd14689c1cd9ee48706eada96a4","status":33,"value":{"message":"session not created exception: Missing or invalid capabilities\\n (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Linux 4.4.0-91-generic x86_64)"}}'
输出摘要 - 返回错误消息说 json
我尝试发送的对象丢失或不正确。
这就是为什么我决定用
mitmproxy
.
它没有内容,但应该有以下 json
内容:
{"desiredCapabilities": {}, "capabilities":{}}
我不明白这是什么问题。我关注了HTTP
规范 - 在每个标题之后我放了 CRLF
( \r\n
) 并在最后一个 header (User-Agent) 之后添加额外的 CRLF
因为正文内容之前必须有 1 个空行。
The request/status line and headers must all end with
<CR><LF>
(that is, a carriage return followed by a line feed). The empty line must consist of only<CR><LF>
and no other whitespace.
最佳答案
您发送的 POST 请求缺少 Content-length
header ,即您发送的请求无效。由于缺少 Content-length
header ,服务器可能无法知道正文在哪里结束,并可能假设根本没有正文,即与预期相去甚远。这也反射(reflect)在您的评论中:“总而言之,响应是说缺少 json 对象”。
我建议使用现有的 HTTP 库,而不是尝试直接使用套接字。 HTTP 比大多数开发人员想象的要复杂。
关于python - HTTP请求内容为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45696981/