我使用
成功地使用pypiwin32发出了一些HTTP GET请求import pythoncom
import win32com.client
pythoncom.CoInitialize()
h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
h.SetAutoLogonPolicy(0) # log in automatically
h.Open('GET', url, True)
h.Send()
稍后从h.status
和h.responseText
pywin32(或者我应该说pypiwin32)似乎没有官方文档,Microsoft WinHttpRequest object docs只有C ++示例。
如何使用pywin32中的win32com.client使用特定的有效负载和Headers发出HTTP POST请求?假设我要添加的HTTP请求标头是
Referer: http://example.com/analysis.aspx?ID=527776455
Cookie: ASP.NET_SessionId=51jrf2r
我要POST的有效负载是
{"Id":"8974552","Action":"Analysis"}
答案 0 :(得分:1)
import pythoncom
import win32com.client
pythoncom.CoInitialize()
h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
h.SetAutoLogonPolicy(0) # log in automatically
h.Open('POST', url, True)
h.SetRequestHeaders(Your_Headers)
h.Send("{"Id":"8974552","Action":"Analysis"}")
答案 1 :(得分:0)
经过一些试验和错误,我认为我做对了。以下是使用httpbin的示例。我发现使用json.dumps()非常方便,因为它会自动将False写为' false'没有' null'。
import json
import win32com.client
h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
h.Open('POST', 'http://httpbin.org/post', True)
h.SetRequestHeader('Referer', 'http://example.com/analysis.aspx?ID=527776455')
h.SetRequestHeader('Cookie', 'ASP.NET_SessionId=51jrf2r')
payload = dict(
Id = 8974552,
Action = "Analysis",
somebool = False,
missing_parameter = None
)
h.Send(json.dumps(payload))
print(h.responseText)
以下是打印命令的输出,其IP地址已删除:
{
"args": {},
"data": "{\"Id\": 8974552, \"Action\": \"Analysis\", \"somebool\": false, \"missing_parameter\": null}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Connection": "close",
"Content-Length": "83",
"Content-Type": "text/plain; Charset=UTF-8",
"Cookie": "ASP.NET_SessionId=51jrf2r",
"Host": "httpbin.org",
"Referer": "http://example.com/analysis.aspx?ID=527776455",
"User-Agent": "Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)"
},
"json": {
"Action": "Analysis",
"Id": 8974552,
"missing_parameter": null,
"somebool": false
},
"origin": "###.###.###.###",
"url": "http://httpbin.org/post"
}