Azure CLI可用的curl命令转PowerShell后报错,求问题排查
问题与解决
问题情况
在Azure CLI中可正常运行的curl命令:
curl https://aoai-try-mc.openai.azure.com/openai/deployments/try-davinci/completions?api-version=2022-12-01 -H "Content-Type:application/json" -H "api-key:keygoeshere" -d '{"prompt":"Tell me a funny story"}'
但在桌面PowerShell中执行等效命令时返回404错误,命令及错误信息如下:
PS C:\Users\manuchadha> curl https://aoai-try-mc.openai.azure.com/openai/deployments/try-davinci/completions?api-version=2022-12-01 -H @{"Content-Type"="application/json" ; "api-key"="keygoeshere"} -Body @{"prompt"="Tell me a funny story"} curl : {"error":{"code":"404","message": "Resource not found"}} At line:1 char:1 + curl https://aoai-try-mc.openai.azure.com/openai/deployments/try-davi ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc eption + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
错误原因及修正
PowerShell中的curl是Invoke-WebRequest的别名,参数规则和原生curl差异很大,你遇到的问题主要来自三个点:
1. URL未正确转义
PowerShell会解析URL中的?作为通配符,导致api-version参数丢失,后端无法匹配正确的API端点,返回404。必须用单引号包裹URL,避免PowerShell解析特殊字符。
2. 请求方法未指定
原生curl在带-d参数时会自动切换为POST请求,但PowerShell的Invoke-WebRequest默认使用GET方法,必须显式指定-Method Post。
3. Body格式错误
直接传入哈希表@{"prompt"="..."}时,PowerShell会默认以application/x-www-form-urlencoded格式发送请求,而Azure OpenAI API要求JSON格式。需要用ConvertTo-Json把哈希表转换成JSON字符串,同时明确指定-ContentType为application/json。
修正后的命令
# 使用Invoke-WebRequest全名 Invoke-WebRequest -Uri 'https://aoai-try-mc.openai.azure.com/openai/deployments/try-davinci/completions?api-version=2022-12-01' ` -Headers @{"api-key"="keygoeshere"} ` -ContentType 'application/json' ` -Method Post ` -Body (ConvertTo-Json @{"prompt"="Tell me a funny story"})
或者使用curl别名:
curl 'https://aoai-try-mc.openai.azure.com/openai/deployments/try-davinci/completions?api-version=2022-12-01' ` -H @{"api-key"="keygoeshere"} ` -ContentType 'application/json' ` -Method Post ` -Body (ConvertTo-Json @{"prompt"="Tell me a funny story"})
内容的提问来源于stack exchange,提问作者Manu Chadha
相关产品推荐
相关产品推荐

