0

I'm trying to add the authentication in the Http header and then do a http post, the target url is a Github API like this: https://api.github.com/user, the code below always response 401, unauthorized, my question is, how to add the authentication in the header? Is the way I did correct?

username = raw_input('Github name: ')
token = raw_input('Access Token: ')
url = 'https://api.github.com/user'
values = {"Username":username,"Password":token}
data = urllib.urlencode(values)
req = urllib2.Request(url,data)
response = urllib2.urlopen(req)
the_page = response.read()
msn
  • 437
  • 1
  • 5
  • 11

1 Answers1

0

You should use urllib2.HTTPPasswordMgrWithDefaultRealm() like that:

import urllib2


gh_url = 'https://api.github.com'

req = urllib2.Request(gh_url)

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

urllib2.install_opener(opener)

handler = urllib2.urlopen(req)

That's a way to consider using the requests library - it's much easier that way:

import requests

r = requests.get('https://api.github.com', auth=('user', 'pass'))
Igor Hatarist
  • 5,234
  • 2
  • 32
  • 45