python urllib2 发布请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16712541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:25:31  来源:igfitidea点击:

python urllib2 post request

pythonurllib2put

提问by Rfraile

Is it posisble to adapt this piece of code for make put request:

是否可以将这段代码改编为 make put 请求:

#!/usr/bin/python

import urllib2, base64, urllib

dir="https://domain.com/api/v1/"
use="[email protected]"
pas="123456"

base64string = base64.encodestring('%s:%s' % (use, pas)).replace('\n', '')

request = urllib2.Request(dir, headers={"Authorization" : "Basic %s" % base64string})
response = urllib2.urlopen(request).read()

print response

I try with this other code, but I think that it do a get request, isn't it?

我尝试使用其他代码,但我认为它执行 get 请求,不是吗?

#!/usr/bin/python

import urllib2, base64, urllib

dir="https://domain.com/api/v1/"
use="[email protected]"
pas="123456"

values = {
      'list' :["201.22.44.12","8.7.6.0/24"]
    }

data = urllib.urlencode(values)

base64string = base64.encodestring('%s:%s' % (use, pas)).replace('\n', '')

request = urllib2.Request(dir, data, headers={"Authorization" : "Basic %s" % base64string})
response = urllib2.urlopen(request).read()

采纳答案by Ashish Jain

I am not sure It will work or not for you but check this piece of code

我不确定它是否适合您,但请检查这段代码

You can encode a dict using urllib like this:

您可以像这样使用 urllib 对 dict 进行编码:

import urllib
import urllib2

url = 'http://example.com/...'
values = { 'productslug': 'bar','qty': 'bar' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
print result