在python中,我如何向网站的服务器发送post请求?

j2datikz  于 2023-02-18  发布在  Python
关注(0)|答案(2)|浏览(172)

我想用python向www.example.com的服务器发送post请求而不是GET请求google.com。
我的代码是:

import socket
from http.server import HTTPServer, BaseHTTPRequestHandler


HOST = 'www.chase.com'
PORT = 80

socket = socket.socket()
socket.connect((HOST, PORT))
socket.send(b"""
GET / HTTP/1.1
Host: chase.com

""")
msg = socket.recv(1024)
print(msg)

有人能帮我向www.example.com发送发帖请求吗google.com?

k10s72fa

k10s72fa1#

您可以使用requests模块:

import requests
data = {"what you want to post":"in form of dict"}
url = "your url"
response = requests.post(url, json=data)

print(response)

之前,您必须运行以下命令来安装requests模块:

pip install requests
n9vozmp4

n9vozmp42#

有人能帮我向www.example.com发送发帖请求吗google.com?
这听起来像urllib.request的任务(它是标准库的一部分),请考虑以下简单示例

import urllib.request
import urllib.parse
data = urllib.parse.urlencode({'x':1,'y':2,'z':3})
data = data.encode('ascii')
with urllib.request.urlopen("http://httpbin.org/post", data) as f:
    print(f.read().decode('utf-8'))

给出输出

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "x": "1", 
    "y": "2", 
    "z": "3"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "11", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.8", 
    "X-Amzn-Trace-Id": "Root=1-63efb182-4f75d5cd47cbe6916985ef10"
  }, 
  "json": null, 
  "origin": "213.134.180.174", 
  "url": "http://httpbin.org/post"
}

我在我的例子中使用了httpbin.org,因为它对调试发送请求很有用,因为它确实以它所得到的响应。注意,你提供的data应该是bytes,所以你需要.encode它,你得到的响应是bytes,所以如果你想要文本(str),你需要.decode它。

相关问题