

import urllib.request
import base64



def getReq(url, user, passw, headers=None):
    try:
        req= urllib.request.Request(url)
        credentials = ('%s:%s' % (user, passw))
        encoded_credentials = base64.b64encode(credentials.encode('ascii'))
        req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
        if headers:
            for h in headers:
                req.add_header(h[1], h[2])
        with urllib.request.urlopen(req) as response:
            return str(response.read())
    except urllib.error.HTTPError as e:
        return str(e)

#format for data {item:content, item:content}
def postReq(url, user, passw, data, headers=None):
    try:
        d = urllib.parse.urlencode(data, quote_via=urllib.parse.quote_plus).encode('utf-8')
        req= urllib.request.Request(url)
        credentials = ('%s:%s' % (user, passw))
        encoded_credentials = base64.b64encode(credentials.encode('ascii'))
        req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
        if headers:
            for h in headers:
                req.add_header(h[0], h[1])
        print(req.headers)
        print(req.get_full_url())
        with urllib.request.urlopen(req) as response:
            return str(response.read())

    except urllib.error.HTTPError as e:
        return str(e)



