【问题标题】:Unsupported Media type error for request.postrequest.post 不支持的媒体类型错误
【发布时间】:2020-05-12 13:26:47
【问题描述】:

我正在使用 python 进行 api 调用。在这里,我有在我试图访问的网站中生成的 json 格式的参数。但是当我尝试运行该程序时,我得到一个415: unsupported Media Type 错误。不知道我做错了什么,因为我使用的是网站生成的参数。

这是我目前的代码

def jprint(obj):
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)


url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'

parameters = {
  "header": {
    "ClientID": "TheClientIDGoesHere",
    "ClientSecret": "TheClientSecretGoesHere"
  },

  "data": {
    "UserName": "Username",
    "Password": "Password",
    "AppKey": "AppKey",
    "ForceRefreshAccessToken": "false"
  }
}

response = requests.post(url, params=parameters)

jprint(response.json())

在上面的代码中,我删除了实际参数并用虚拟文本替换它们。但是当我用实际参数尝试它们时,我得到以下错误

{
    "status": 415,
    "title": "Unsupported Media Type",
    "traceId": "|df46105a-49e1b43f80675626.",
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13"
}

我改变的一件事是这个代码"ForceRefreshAccessToken": "false"。在生成的 json 代码中,false 不在引号内

不知道我做错了什么。请帮帮我。

【问题讨论】:

  • 也许header 不应该出现在实际的http 标头中?还要确保ClientID 不应该是client_id 或类似的东西
  • 你是对的。它实际上是client_id 和client_secret。但我不认为这是错误的原因。当我尝试@Ahmet 答案时,错误消失了。但我现在面临另一个错误。

标签: python json api http-status-code-415


【解决方案1】:
import requests
import json


def jprint(obj):
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)


url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'

parameters = {
    "header": {
        "ClientID": "TheClientIDGoesHere",
        "ClientSecret": "TheClientSecretGoesHere"
    },

    "data": {
        "UserName": "Username",
        "Password": "Password",
        "AppKey": "AppKey",
        "ForceRefreshAccessToken": False
    }
}

hdr = {"Content-Type": "application/json"}

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

print(response.status_code)

print(response.json())

错误 415 表示该站点不支持该媒体类型。这可以通过在标头中明确声明内容类型将为 JSON 来解决。 hdr = {"Content-Type": "application/json"} 该站点的响应代码是“200:OK”,因此您的请求有效。

【讨论】:

  • 我尝试了愚蠢的答案。我丢失了 415 错误消息,但收到以下错误 "ErrorMessage": "'h' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
  • 这是parameters 中'header' 中的'h'。您没有以 API 期望的格式发送数据,因此它无法解析它。尽管从200:OK 响应状态可以看出请求正在工作。我不知道 API,因此无法提供进一步的帮助。
  • 如果我解决了您所面临的错误,请接受答案,如问题中所述
猜你喜欢
  • 2014-11-11
  • 2018-10-13
  • 2018-07-25
  • 2016-09-09
  • 2015-08-11
  • 2017-08-28
  • 2015-06-18
  • 2021-10-12
  • 2017-10-23
相关资源
最近更新 更多