AlixaProDev
AlixaProDev

Reputation: 568

How to pass Auth in a "get" request using urllib.request Python

To make a get request with Python I was using urllib.request.urlopen(url) but I am having problem passing username and password to http://httpbin.org/basic-auth/ali/pass

enter image description here

import urllib.request
data={"user": "ali","passwd":"pass"}

data = urllib.parse.urlencode(data)
data = data.encode('utf-8')

url = "http://httpbin.org/basic-auth/ali/pass"
response = urllib.request.Request(url,data=data)

print(urllib.request.urlopen(response))

Upvotes: 0

Views: 804

Answers (1)

AlixaProDev
AlixaProDev

Reputation: 568

I tried using requests module which work perfectly but I am trying to learn about urllib.request module so that is why.

from requests.auth import HTTPBasicAuth
import requests
r=requests.get('http://httpbin.org/basic-auth/ali/pass', auth=HTTPBasicAuth('ali', 'pass'))
print(r.status_code)

Upvotes: 1

Related Questions