问题描述
Python 脚本:
HEADERS = {'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY}
file = {'image' : ('myfile',open(imagePath,'rb'))}
def print_json(obj):
"""Print the object as json"""
print(json.dumps(obj,sort_keys=True,indent=2,separators=(',',': ')))
try:
response = requests.post(BASE_URI,headers=HEADERS,files=file)
response.raise_for_status()
print_json(response.json())
except Exception as ex:
raise ex
Python 脚本结果:https://pastebin.com/3N3BTgPU
PHP 脚本:
$ch = curl_init();
$img = curl_file_create($imagepath);
$post = ["image" => $img];
curl_setopt($ch,CURLOPT_URL,self::endpoint);
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type: multipart/form-data','Ocp-Apim-Subscription-Key: ' . self::API_KEY,));
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
$contents = curl_exec($ch);
echo "$contents";
PHP 脚本结果:https://pastebin.com/c2tKwgBV
我可以确认两个脚本使用相同的端点、API 密钥和相同的图像。 我在 PHP 中做错了什么?
解决方法
我不懂 PHP,但您确定在这两种情况下都将相同的有效负载传递给 post 端点吗?尝试打印两个有效负载并进行比较。
蟒蛇:
# a dict with key and value(a tuple with 'myfile' and image)
file = {'image' : ('myfile',open(imagePath,'rb'))}
PHP:
# a list (?)
$post = ["image" => $img];