Doing POSTs with Python Modules

From PeformIQ Upgrade
Jump to navigation Jump to search

HTTPS GET to https://api.aasdev.net/api/ONLINE/Questions/

#!/usr/bin/env python


import ssl
import base64
import urllib2


from urllib2 import Request, urlopen, URLError, HTTPError


ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

request = Request('https://api.aasdev.net/api/ONLINE/Questions/?Auth=Yes')

try:
    #r = urlopen(req, context=ctx)
    response = urlopen(request, context=ssl._create_unverified_context())

    response_data = response.read()
    status_code   = response.code

    print status_code
    print response_data

except URLError, e:

    if hasattr(e, 'reason'):
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):
        print "The server couldn't fulfill the request."
        print 'Error code: ', e.code
    else:
        pass

    #print e.read()

With SSL Basic Authentication

#!/usr/bin/env python


import ssl
import base64
import urllib2


from urllib2 import Request, urlopen, URLError, HTTPError

username = 'plh'
password = 'XXXXX'

auth_encoded = base64.encodestring('%s:%s' % (username, password))[:-1]

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

request = Request('https://api.aasdev.net/api/ONLINE/Questions/?Auth=Yes')

request.add_header('Authorization', 'Basic %s' % auth_encoded)

try:
    # response = urlopen(req, context=ctx)
    response = urlopen(request, context=ssl._create_unverified_context())

    response_data = response.read()
    status_code   = response.code

    print status_code
    print response_data

except URLError, e:

    if hasattr(e, 'reason'):
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):
        print "The server couldn't fulfill the request."
        print 'Error code: ', e.code
    else:
        pass

    #print e.read()

Doing a POST