Search code examples
pythonapigeturlliburllib2

python using urllib2 and urllib get request issue


when i use curl get request success,but using python call get request failed, anyone can help!

shell script:
curl -X GET -H 'Content-type: application/json' -H 'Authorization: Bearer '$token'' -d '[ { "id":"535985", "language":"EN", "Detailes":{"LibraryId":"KF_2gl9xZYKX7TJi66" }, "KeyID":"SF_cY1tKhYiocNluBB" } ]' 'https://XXXX.com'

get request success.

python Script:
data ={ "id":"535985", "language":"EN", "Detailes":{"LibraryId":"KF_2gl9xZYKX7TJi66" }, "KeyID":"SF_cY1tKhYiocNluBB" }
headers = {'content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer %s' % (token)}
proxy = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
DataForGet=urllib.urlencode(data)
NewUrl= apilink + "?" + DataForGet
request = urllib2.Request(NewUrl, headers)
response = urllib2.urlopen(request, timeout=300)
message = response.read()

the return message TypeError: unhashable type

anyone know how to use get request by urllib2 and urllib model. Many thanks!


Solution

  • I found we can define this mothod to call api get data

    class RequestMethod(urllib2.Request,object):
        def __init__(self, url, method=None,data=None, headers={},origin_req_host=None, unverifiable=False):
            self.method = method
            super(RequestMethod,self).__init__(url, data=data,headers=headers,origin_req_host=origin_req_host,unverifiable=unverifiable)
        def get_method(self):
            if self.method != None:
                return self.method
            else:
                return super(RequestMethod,self).get_method()
        def set_method(self,method):
            self.method = method
        def setMethodRequest(url,method):
            return RequestMethod(url,method=method)