天天看点

python urllib2发http请求_使用python urllib / urllib2发出一个http POST请求来上传文件

我想发一个POST请求,使用python将文件上传到Web服务(并得到响应).例如,我可以使用curl执行以下POST请求:

curl -F "[email protected]" -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 Error 500.但是因为我的curl命令成功了,我的python请求一定是错的?

我对这个话题很陌生,如果菜鸟问题有很简单的答案或错误,请原谅我.在此先感谢您的所有帮助!

解决方法:

我个人认为你应该考虑requests库发布文件.

url = 'http://jigsaw.w3.org/css-validator/validator'

files = {'file': open('style.css')}

response = requests.post(url, files=files)

标签:python,post,http,urllib,urllib2

来源: https://codeday.me/bug/20190930/1835645.html