【发布时间】:2015-01-18 22:50:43
【问题描述】:
我想使用 Python 发出 POST 请求以将文件上传到 Web 服务(并获得响应)。例如,我可以使用curl 执行以下 POST 请求:
curl -F "file=@style.css" -F output=json http://jigsaw.w3.org/css-validator/validator
如何使用 python urllib/urllib2 发出相同的请求?到目前为止,我得到的最接近的是:
with open("style.css", 'r') as f:
content = f.read()
post_data = {"file": content, "output": "json"}
request = urllib2.Request("http://jigsaw.w3.org/css-validator/validator", \
data=urllib.urlencode(post_data))
response = urllib2.urlopen(request)
我从上面的代码中得到了 HTTP 错误 500。但是既然我的curl命令成功了,那一定是我的python请求有问题吧?
我对这个话题很陌生,我的问题可能有非常简单的答案或错误。
【问题讨论】:
标签: python http post urllib2 urllib