Python Requests, getting back: Unexpected character encountered while parsing value: L. Path

五迷三道 提交于 2021-02-08 07:43:21

问题


I am attempting to get an auth token from The Trade Desk's (sandbox) api but I get back a 400 response stating:

"Error reading Content-Type 'application/json' as JSON: Unexpected character encountered while parsing value: L. Path '', line 0, position 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.'}

My script (runnable):

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

Sandbox docs here

I believe this means my headers var is not being serialized correctly by requests, which seems impossible, or not being deserialized correctly by The Trade Desk. I've gotten into the requests lib but I can't seem to crack it and am looking for other input.


回答1:


You need to do

import json

and convert your dict into json:

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

Another way would be to explicitely use json as parameter:

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

Background: In the prepare_body method of requests a dictionary is explicitely converted to json and a content-header is also automatically set:

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

If you pass data=data then your data will be only form-encoded (see http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests). You will need to explicitely convert it to json, if you want json to be the content-type of your http body.

Your follow-up question was about why headers don't have to be converted to json. Headers can be simply passed as dictionary into the request. There's no need to convert it to json. The reason is implementation specific.



来源:https://stackoverflow.com/questions/34051500/python-requests-getting-back-unexpected-character-encountered-while-parsing-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!