405尝试使用发送消息API终结点时出错

2024-10-01 04:51:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python的请求包和以下代码:

APIKEY = "XXX"
url = 'https://services.kommunicate.io/rest/ws/message/v2/send HTTP/1.1'

myobj = {
    'groupId': "xxx",
    'message':'Hello',
    "fromUserName":'yyy'
        }

headers = {
    'Api-Key':APIKEY,
}
response = requests.post(url, data = myobj,headers=headers)

并且给了我以下错误:

'{"status":"error","errorResponse":[{"errorCode":"AL-MA-01","description":"method not allowed","displayMessage":"Request method \\u0027POST\\u0027 not supported"}],"generatedAt":1591385905404}'

我做错了什么


Tags: 代码httpsioresturlmessagewsservice
1条回答
网友
1楼 · 发布于 2024-10-01 04:51:11

代码中几乎没有问题
1. HTTP/1.1不是URL的一部分。
2.在requests包中,为了向服务器传递JSON,有多种方法

a。使用requests.post方法中提供的json参数将JSON数据发送到服务器,类似以下代码:

import requests

APIKEY = "XXX"
url = 'https://services.kommunicate.io/rest/ws/message/v2/send'
myobj = {
    'groupId': "xxx",
    'message': 'Hello',
    "fromUserName": 'yyy'
}

headers = {'Api-Key': APIKEY}

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

b。在标题中添加"Content-Type": "application/json",然后首先将json数据转储到字符串,然后将其发送到服务器

import requests
import json 

APIKEY = "XXX"
url = 'https://services.kommunicate.io/rest/ws/message/v2/send'
myobj = {
    'groupId': "xxx",
    'message': 'Hello',
    "fromUserName": 'yyy'
}

headers = {
    'Api-Key': APIKEY,
    "Content-Type": "application/json"
}

myobj = json.dumps(myobj)

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

另外,请检查Difference between data and json parameters in python requests package

相关问题 更多 >