gpt4 book ai didi

Python socket 客户端 Post 参数

转载 作者:太空狗 更新时间:2023-10-30 02:10:38 24 4
gpt4 key购买 nike

首先让我清楚我不想使用更高级别的API,我只想使用套接字编程

我编写了以下程序来使用 POST 请求连接到服务器。

import socket
import binascii

host = "localhost"
port = 9000
message = "POST /auth HTTP/1.1\r\n"
parameters = "userName=Ganesh&password=pass\r\n"
contentLength = "Content-Length: " + str(len(parameters))
contentType = "Content-Type: application/x-www-form-urlencoded\r\n"

finalMessage = message + contentLength + contentType + "\r\n"
finalMessage = finalMessage + parameters
finalMessage = binascii.a2b_qp(finalMessage)


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(finalMessage)

print(s.recv(1024))

我在网上查看了 POST 请求是如何创建的。

不知何故,参数没有传递到服务器。我是否必须在请求之间添加或删除“\r\n”?

提前致谢,问候,象头神。

最佳答案

这一行 finalMessage = binascii.a2b_qp(finalMessage) 肯定是错误的,所以你应该完全删除该行,另一个问题是 Content-Length 之后没有换行。在这种情况下,发送到套接字的请求是(我在这里将 CRLF 字符显示为 \r\n,但也会拆分线条清晰):

POST /auth HTTP/1.1\r\n
Content-Length: 31Content-Type: application/x-www-form-urlencoded\r\n
\r\n
userName=Ganesh&password=pass\r\n

很明显,这对网络服务器来说意义不大。


但即使在添加换行符并删除 a2b_qp 之后,问题仍然是您不是 talking HTTP/1.1那里;请求必须具有 HTTP/1.1 (RFC 2616 14.23) 的 Host header :

A client MUST include a Host header field in all HTTP/1.1 request messages . If the requested URI does not include an Internet host name for the service being requested, then the Host header field MUST be given with an empty value. An HTTP/1.1 proxy MUST ensure that any request message it forwards does contain an appropriate Host header field that identifies the service being requested by the proxy. All Internet-based HTTP/1.1 servers MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message which lacks a Host header field.

此外,您不支持分块请求和持久连接、keepalive 或任何东西,因此您必须执行 Connection: close (RFC 2616 14.10):

HTTP/1.1 applications that do not support persistent connections MUST include the "close" connection option in every message.

因此,任何在没有 Host: header 的情况下仍能正常响应您的消息的 HTTP/1.1 服务器也已损坏。

这是您应该随该请求发送到套接字的数据:

POST /auth HTTP/1.1\r\n
Content-Type: application/x-www-form-urlencoded\r\n
Content-Length: 29\r\n
Host: localhost:9000\r\n
Connection: close\r\n
\r\n
userName=Ganesh&password=pass

请注意,您不再在正文中添加 \r\n(因此正文的长度为 29)。此外,您应该阅读响应以找出您遇到的错误。


在 Python 3 上,工作代码会说:

host = "localhost"
port = 9000

headers = """\
POST /auth HTTP/1.1\r
Content-Type: {content_type}\r
Content-Length: {content_length}\r
Host: {host}\r
Connection: close\r
\r\n"""

body = 'userName=Ganesh&password=pass'
body_bytes = body.encode('ascii')
header_bytes = headers.format(
content_type="application/x-www-form-urlencoded",
content_length=len(body_bytes),
host=str(host) + ":" + str(port)
).encode('iso-8859-1')

payload = header_bytes + body_bytes

# ...

socket.sendall(payload)

关于Python socket 客户端 Post 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com