Python 请求,返回:解析值时遇到意外字符:L.Path

2024-04-22

我试图从 The Trade Desk 的(沙盒)api 获取身份验证令牌,但收到 400 响应,指出:

“将内容类型‘application/json’读取为 JSON 时出错:意外 解析值时遇到的字符:L.Path '',第 0 行, 位置 0。”

Whole response.json():

{u'ErrorDetails': [{u'Reasons': [u"Error reading Content-Type 'application/json' as JSON: Unexpected character encountered while parsing value: L. Path '', line 0, position 0."], u'Property': u'TokenRequest'}], u'Message': u'The request failed validation. Please check your request and try again.'}

我的脚本(可运行):

import requests

def get_token():

    print "Getting token"
    url = "https://apisb.thetradedesk.com/v3/authentication"

    headers = {'content-type': 'application/json'}

    data = {
              "Login":"logintest",
              "Password":"password",
              "TokenExpirationInMinutes":60
            }

    response = requests.post(url, headers=headers, data=data)

    print response.status_code
    print response.json()

    return

get_token()

沙箱文档在这里 https://apisb.thetradedesk.com/v3/doc

我相信这意味着我的headersvar 没有被正确序列化requests,这似乎不可能,或者 The Trade Desk 没有正确反序列化。我已经进入了requestslib,但我似乎无法破解它,正在寻找其他输入。


你需要做

import json

并将你的 dict 转换为 json:

response = requests.post(url, headers=headers, data=json.dumps(data))

另一种方法是明确使用json作为参数:

response = requests.post(url, headers=headers, json=data)

背景: In the prepare_bodyrequests 的方法将字典显式转换为 json,并且还会自动设置内容标头:

if not data and json is not None:
        content_type = 'application/json'
        body = complexjson.dumps(json)

如果你通过了data=data那么你的数据将只是形式编码(参见http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests)。如果您希望 json 成为 http 正文的内容类型,则需要将其显式转换为 json。

您的后续问题是关于为什么标头不必转换为 json。标头可以简单地作为字典传递到请求中。无需将其转换为 json。原因是特定于实现的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 请求,返回:解析值时遇到意外字符:L.Path 的相关文章

随机推荐