如何使用pythonapi获取请求

2024-09-28 15:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的函数从web获取数据,但失败了。我想知道urllib.quote是否用错了

我用过urllib.urlencode(xx),但它显示了not a valid non-string sequence or mapping object

我的请求数据是:

[{"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}]

任何人都可以帮忙。谢谢!!!你知道吗

###This Funcation call API Post Data
def CallApi(apilink, indata):
    token = gettoken()
    data = json.dumps(indata, ensure_ascii=False)
    print(data)
    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.quote(data)
    NewUrl= apilink + "?" + DataForGet
    request = urllib2.Request(NewUrl, headers=headers)
    response = urllib2.urlopen(request, timeout=300)
    message = response.read()
    print(message)

错误:

the err message below: File "/opt/freeware/lib/python2.7/urllib2.py", line 1198, in do_open raise URLError(err)


Tags: tokenjsonmessagedataapplicationopenerurllib2urllib
1条回答
网友
1楼 · 发布于 2024-09-28 15:31:53

您可以看到urlencode的注释

Encode a dict or sequence of two-element tuples into a URL query string

因此您可以选择移除外部[]

{"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}

或者使用两元素元组

(('Keys', 'SV_cY1tKhYiocNluHb'), ('Details', [{...}]...)

演示

>>> import urllib
>>> s = {"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}
>>> urllib.urlencode(s)
'Keys=SV_cY1tKhYiocNluHb&Details=%5B%7B%27id2%27%3A+%27PK_2gl9xtYKX7TJi29%27%7D%5D&language=EN&id=535985'
>>> 

相关问题 更多 >