The HTTP 401 unauthorized error is returned when Python simulates an HTTPS request.
The HTTP 401 unauthorized error is returned when Python simulates an HTTPS request.
In the Python Web, the rest api usage example-an online translation tool built on the Cloud Platform + cloud service, using Python to simulate HTTPS requests;
The httplib module is used at the beginning. The Code is as follows:
header = {"Content-type": "application/json", "Accept": "*/*" }params = { 'source':'en', 'target':'es', 'text':match.group(1) } data = urllib.urlencode(params)surl = urlparse('https://gateway.watsonplatform.net/language-translation/api/v2/translate')#surl = urlparse('https://www.baidu.com/')resContent = ''try:conn = httplib.HTTPSConnection(surl.netloc) conn.request('GET', surl.path + '?' + data)response = conn.getresponse()resContent = data + "" + getAllAttrs(response) #response.read() #except:info=sys.exc_info()resContent = getAllAttrs(info[0]) + getAllAttrs(info[1])
After some searches, it was found that httplib does not support such requests that require authentication;
The following code is successfully changed:
Params = {'source': 'en', 'target': 'els', 'text': match. group (1)} surl = 'https: // gateway.watsonplatform.net/language-translation/api/v2/translate? '+ Urllib. urlencode (params) resContent = ''try: passman = urllib2.HTTPPasswordMgrWithDefaultRealm () # create a Domain Verification object passman. add_password (None, surl, "c9819718-4660-441c-9df7-07398950ea44", "qUvrJPSdPgOx") # Set the domain address, user name and password auth_handler = urllib2.HTTPBasicAuthHandler (passman) # generate a handler for processing authentication with remote hosts opener = urllib2.build _ opener (auth_handler) # Return an openerDirector instance urllib2.install _ opener (opener) # Install an openerDirector instance By default. Response = urllib2.urlopen (surl) # Open the URL link and return the Response object resContent = response. read () # read response content failed T: info = sys. exc_info () resContent = getAllAttrs (info [0]) + getAllAttrs (info [1]) # obtain exception details
The following modules support authentication requests:
Httplib2, urllib2, requests, pycurl
But the Python 2.7.10 I installed only includes urllib2 by default, so I chose to use it.