【问题标题】:Python 3 - POST request with urllib.request returning HTML dataPython 3 - 带有 urllib.request 的 POST 请求返回 HTML 数据
【发布时间】:2014-09-09 01:07:36
【问题描述】:

我正在尝试使用 POST 请求访问网站的 API,但它返回 HTML,我不知道为什么。

import urllib.request
url = 'https://matchbook.com'
loginReq = '"method": "/bpapi/rest/security/session", "params":{"username": "xxxxx","password": "xxxxx"}'

req = urllib.request.Request(url, loginReq.encode('utf-8'))
response = urllib.request.urlopen(req).read()
print (response)    

这会返回一个 HTML 流,基本上表明我正在使用不受支持的 Internet Explorer 版本,我应该考虑升级到更新的版本。

我花了一些时间在网上查找,很难找到有关 Python 3 中的 get/post/put/delete 请求的任何详细信息,我发现的大多数有用信息都涉及使用 Python 中的“请求”模块2. 切换到 Python 2 会更容易吗?

这是他们在文档中提供的信息:

资源网址: 网址:matchbook.com URN:/bpapi/rest/security/session

示例请求: 发布/安全/会话 { “用户名”:“j_henry”, "密码": "**" }

示例响应: { “会话令牌”:“1418_1234567890”, “用户 ID”:1418, "account": { // 与 GET /account API 响应相同。 ... }

【问题讨论】:

    标签: python api post python-3.x urllib


    【解决方案1】:

    问题几乎可以肯定是您错误地向 API 发送数据;也就是你的 loginReq 变量。

    您需要使用 curl 或一些等效工具来准确确定需要发布哪些参数和值。类似于

    curl --data "method:/bpapi/rest/security/session&params={username=j_henry&password=**}" https://www.matchbook.com
    

    一旦你完成了请求,你就可以开始担心实际编程了。

    【讨论】:

    • 不知何故直到现在我才看到您的回复,但感谢您抽出时间回复,您是正确的,因为我没有正确传递参数。我最终切换到 requests 模块,因为它比 urllib 更直接。 requests.post(url, data=json.dumps(loginReq), headers=mbHeader).json(),data和header都是字典,搞定了。
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多