使用Python发送HTTP Post

时间:2017-02-26 19:30:55

标签: python http post

我想创建一个程序,我可以发送HTTP post请求并做出响应。

所以,我想发这个帖子:

POST https: //example.com/index.php?s=&&app=box&module=ajax&section=coreAjax&secure_key=&type=submit&lastid=87311&global=1 HTTP/1.1
Host: example.com
Connection: keep-alive
Content-Length: 10
Accept: text/javascript, text/html, application/xml, text/xml, */*
X-Prototype-Version: 1.7.2
Origin: https://example.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Content-type: application/x-www-form-urlencoded; charset=UTF-8
Referer: https://x.com/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: cookieconsent_status=dismiss; 

然后输入请求正文:

message=                    # Which I will make: "message= %s" % (messagex))

但是我不知道如何发送它们,似乎无法在网上找到任何方式,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

主要部分是:

import requests # you have to install this library, with pip for example

# define your custom headers (as many as you want)

headers = {
  'X-Prototype-Version': '1.7.2'
}

# define your URL params (!= of the body of the POST request)

params = {
  'your_first_param': 'its_value',
  'your_second_param': 'its_value'
}

# define the body of the POST request

data = {
  'message' : 'your message'
}

# send the POST request

response = requests.post('https://example.com/index.php', params=params, data=data, headers=headers)

# here is the response

print response.text

希望有所帮助。