Microsoft Face API是微软认知服务(Cognitive Services)的一部分,提供人脸检测、识别、验证和分组等功能。400错误通常表示客户端发送的请求存在格式或内容问题,服务器无法处理。
原因:请求正文不符合API要求的JSON格式规范。
解决方案:
Content-Type: application/json
// 正确示例
{
"url": "https://example.com/image.jpg"
}
// 错误示例(缺少引号)
{
url: "https://example.com/image.jpg"
}
原因:缺少API操作所需的必填字段。
解决方案:
url
或data
字段原因:提供的图像URL无法访问或格式不正确。
解决方案:
原因:直接上传的图像数据格式不正确或损坏。
解决方案:
原因:图像文件过大(通常限制为4MB或6MB)。
解决方案:
import requests
import json
# 正确的API调用示例
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://YOUR_REGION.api.cognitive.microsoft.com/face/v1.0/detect"
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscription_key
}
params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,emotion'
}
body = {
'url': 'https://example.com/person.jpg'
}
try:
response = requests.post(endpoint, headers=headers, params=params, json=body)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
print(f"Response: {err.response.text}")
except Exception as err:
print(f"Error: {err}")
遇到400错误时,仔细检查请求正文内容是最关键的解决步骤。
没有搜到相关的沙龙