我正在尝试使用python原始套接字在URL上执行http帖子。但是我无法这样做,而http get请求正常工作。 问题是当我尝试发帖时。
我的代码
import socket
HOST = 'www.example.com'
PORT = 80
DATA = "POST /example/email.php HTTP/1.1\r\n" # send headers
"HOST: example.com\r\n"
"Accept: */\r\n*"
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"
"Referer: http://example.com/example/\r\n"
"action=subscribeme&email=laaarr@gmail.com\r\n" #actual post payload data
def tcp_client():
client = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
client.connect(( HOST, PORT ))
client.send(DATA)
response = client.recv(4096)
print response
if __name__ == '__main__':
tcp_client()
服务器端没有错误/回复(错误的请求或其他任何东西),但它似乎无法正常工作。其他一切都是正确的,因为我在POSTMAN和curl上检查了它们。
答案 0 :(得分:1)
尝试
DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers
"HOST: example.com\r\n"
"Accept: *\r\n"
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"
"Referer: http://example.com/example/\r\n"
"\r\n" # blank line seperating headers from body
"action=subscribeme&email=laaarr@gmail.com\r\n") #actual post payload data
你应该得到答案。
使用
import socket
HOST = 'www.example.com'
PORT = 80
DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers
"HOST: example.com\r\n"
"Accept: *\r\n"
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"
"Referer: http://example.com/example/\r\n"
"\r\n" # blank line seperating headers from body
"action=subscribeme&email=laaarr@gmail.com\r\n") #actual post payload data
def tcp_client():
client = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
client.connect(( HOST, PORT ))
client.send(DATA)
response = client.recv(4096)
print response
if __name__ == '__main__':
tcp_client()
我得到了
HTTP/1.1 411 Length Required
Content-Type: text/html
Content-Length: 357
Connection: close
Date: Mon, 08 Aug 2016 11:23:16 GMT
Server: ECSF (ewr/1443)
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>411 - Length Required</title>
</head>
<body>
<h1>411 - Length Required</h1>
</body>
</html>
这显然是一个错误但完全是一个回应。
用
DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers
"HOST: example.com\r\n"
"Accept: *\r\n"
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"
"Content-Length: 41\r\n" #fixes error 411
"Referer: http://example.com/example/\r\n"
"\r\n" # blank line seperating headers from body
"action=subscribeme&email=laaarr@gmail.com") #actual post payload data
我得到正常的404 Not Found
。