使用 python 发布 json 数据时出现问题
Problem when posting json data with python
我正在尝试从 LeetCode-CN 获取我提交的所有代码,我需要获取问题的翻译。下面的 curl 命令可以给我想要的结果:
curl 'https://leetcode-cn.com/graphql' -H 'authority: leetcode-cn.com' -H 'origin: https://leetcode-cn.com' -H 'content-type: application/json' -H 'referer: https://leetcode-cn.com/problemset/all/' --data '{"operationName":"getQuestionTranslation","variables":{},"query":"query getQuestionTranslation($lang: String) {\n translations: allAppliedQuestionTranslations(lang: $lang) {\n title\n questionId\n __typename\n }\n}\n"}'
但是下面的python代码不能工作:
def loadChnProblemList(client):
query = {
"operationName": "getQuestionTranslation",
"variables": {},
"query": "query getQuestionTranslation($lang: String) {\n translations: allAppliedQuestionTranslations(lang: $lang) {\n title\n questionId\n __typename\n }\n}\n"}
headers = {
"content-type": "application-json",
"origin": "https://leetcode-cn.com",
"referer": "https://leetcode-cn.com/problemset/all/"
}
response = requests.post("https://leetcode-cn.com/graphql", headers=headers, data=json.dumps(query))
data = json.loads(response.text)
print(data)
服务器将响应:
{"errors":[{"message":"Must provide query string."}]}'
为什么 curl 命令有效但 python 代码无效?
Shijith 是正确的 - 将内容类型更改为 application/json 是解决方法。有关详细信息,请参阅 requests docs。
我正在尝试从 LeetCode-CN 获取我提交的所有代码,我需要获取问题的翻译。下面的 curl 命令可以给我想要的结果:
curl 'https://leetcode-cn.com/graphql' -H 'authority: leetcode-cn.com' -H 'origin: https://leetcode-cn.com' -H 'content-type: application/json' -H 'referer: https://leetcode-cn.com/problemset/all/' --data '{"operationName":"getQuestionTranslation","variables":{},"query":"query getQuestionTranslation($lang: String) {\n translations: allAppliedQuestionTranslations(lang: $lang) {\n title\n questionId\n __typename\n }\n}\n"}'
但是下面的python代码不能工作:
def loadChnProblemList(client):
query = {
"operationName": "getQuestionTranslation",
"variables": {},
"query": "query getQuestionTranslation($lang: String) {\n translations: allAppliedQuestionTranslations(lang: $lang) {\n title\n questionId\n __typename\n }\n}\n"}
headers = {
"content-type": "application-json",
"origin": "https://leetcode-cn.com",
"referer": "https://leetcode-cn.com/problemset/all/"
}
response = requests.post("https://leetcode-cn.com/graphql", headers=headers, data=json.dumps(query))
data = json.loads(response.text)
print(data)
服务器将响应:
{"errors":[{"message":"Must provide query string."}]}'
为什么 curl 命令有效但 python 代码无效?
Shijith 是正确的 - 将内容类型更改为 application/json 是解决方法。有关详细信息,请参阅 requests docs。