python中调用API的几种方式:
- urllib2
- requests
一、调用别人的接口
案例1、urllib2
importurllib2, urllib
github_url='https://api.github.com/user/repos'password_manager=urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None,github_url,'user', '***')
auth=urllib2.HTTPBasicAuthHandler(password_manager)#create an authentication handler
opener = urllib2.build_opener(auth)#create an opener with the authentication handler
urllib2.install_opener(opener)#install the opener
...
request=urllib2.Request(github_url,
urllib.urlencode({'name': 'Test repo','description': 'Some test repository'}))#Manual encoding required
handler =urllib2.urlopen(request)print handler.read()
案例2、requests
importrequests, json
github_url= "da