我试图使用python中的requests模块复制以下POST请求:
POST /example/asdfas HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------241652170216373
Content-Length: 279
-----------------------------241652170216373
Content-Disposition: form-data; name="value_1"
12345
-----------------------------241652170216373
Content-Disposition: form-data; name="value_2"
67890
-----------------------------241652170216373--
requests的文档建议使用files参数。
当我尝试以下调用时:
import requests
requests.post('http://example.com/example/asdfas', files={'value_1': '12345',
'value_2': '67890'})
我收到以下HTTP请求:
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, compress',
'Content-Length': '264',
'User-Agent': 'python-requests/2.2.1 CPython/3.3.2 Windows/7',
'Content-Type': 'multipart/form-data; boundary=273f13699c02429db4eb95c97f757d38'
--273f13699c02429db4eb95c97f757d38
Content-Disposition: form-data; name="value_1"; filename="value_1"
12345
--273f13699c02429db4eb95c97f757d38
Content-Disposition: form-data; name="value_2"; filename="value_2"
67890
--273f13699c02429db4eb95c97f757d38--
我还尝试使用数据参数:
import requests
requests.post('http://example.com/example/asdfas', data={'value_1': '12345',
'value_2': '67890'})
导致以下HTTP请求:
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': '27',
'User-Agent': 'python-requests/2.2.1 CPython/3.3.2 Windows/7',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, compress'
value_2=67890&value_1=12345
我遇到的问题是,使用files参数会导致服务器无法识别调用,可能是由于HTTP请求中发送了意外的“filename”信息。使用data参数发送错误的内容类型头。
已知第一个请求正在我希望将请求发送到的服务器上工作-要完全复制第一个HTTP请求,正确的函数调用是什么?
编辑: 复制工作请求的HTML表单示例:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="http://example.com/example/asdfas" method="post" enctype="multipart/form-data">
<label for="v1">Value 1</label>
<input id="v1" type="text" name="value_1">
<label for="v2">Value 2</label>
<input id="v2" type="text" name="value_2">
<input type="submit">
</form>
</body>
</html>
解决方案是在向files参数传递参数时使用元组:
按预期工作:
相关问题 更多 >
编程相关推荐