【问题标题】:python using urllib2 and urllib get request issuepython使用urllib2和urllib获取请求问题
【发布时间】:2019-11-22 04:59:22
【问题描述】:

当我使用 curl 获取请求成功,但使用 python 调用获取请求失败时,任何人都可以提供帮助!

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'

获取请求成功。

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()

返回消息 TypeError: 不可散列的类型

任何人都知道如何使用 urllib2 和 urllib 模型获取请求。非常感谢!

【问题讨论】:

  • 为什么不使用requests
  • 因为服务器 python 版本是 2.7,我们无法访问 pip install requests 模型
  • edit您的问题包含完整的回溯。

标签: python api get urllib urllib2


【解决方案1】:

我发现我们可以定义这个方法来调用api获取数据

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)

【讨论】:

    猜你喜欢
    • 2018-02-04
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2015-01-18
    • 2016-09-18
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多