2017-02-26 137 views
0

我想製作一個程序,可以發送HTTP發佈請求並進行響應。用Python發送HTTP帖子

所以,我要發這個帖子:

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

你有看過http://requests.readthedocs.io/en/master/?或者httplib庫? – ValLeNain

+0

@ValLeNain是的,但我對Python真的很陌生,並且對如何做到這一點不太瞭解:/ – Hubgum

+0

閱讀段落自定義標題和更復雜的POST請求(http://requests.readthedocs.io/en/master/user/quickstart /#custom-headers)這正是你所需要的,非常簡單。請記住,在發佈StackOverflow之前,你必須嘗試一些東西;) – ValLeNain

回答

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 

希望有所幫助。