Python套接字客户端Post参数

2024-04-29 10:47:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如果让我说清楚我不想使用更高级别的api,我只想使用socket编程

我已经编写了以下程序来使用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”?

提前谢谢你, 当做, 甘尼什。


Tags: import服务器apihostmessageport编程socket
1条回答
网友
1楼 · 发布于 2024-04-29 10:47:30

这一行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

显然,这对web服务器没有多大意义。


但是,即使在添加新行并删除a2b_qp之后,仍然存在的问题是,您不是那里的而不是talking ^{};对于HTTP/1.1,请求必须有一个Host头(RFC 2616 14.23):

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.

此外,您不支持分块请求和持久连接、keepalives或任何内容,因此必须执行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:头,任何仍能正常响应消息的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)

相关问题 更多 >