使用Invoke-RestMethod为Microsoft Cognitive API获取400个错误的请求错误

时间:2016-07-02 17:39:38

标签: powershell microsoft-cognitive

我们正在尝试从Microsoft的Cognitive服务测试和评估Text Analysis API。我们正在尝试使用Invoke-RestMethod来运行快速而脏的PowerShell脚本。经过一些调整后,我们仍然会收到400条错误。我们不确定是什么问题,因为JSON似乎已得到纠正,我们输入的API密钥似乎是正确的。我们已经利用了我们在另一个人的博客上发现的有关使用附加标题的内容,并尝试了一些变体,但仍然没有骰子。有人可以为我们做一次健全检查吗?

#html tag stripper function
function htmlStrip ($results)
    {
    #using .NET toString method to ensure PS doesn't interpret same var incorrectly
    $results = $results.toString()
    $results -replace '<[^>]*(>|$)'
    }


Try
{


    [string]$sourceUrl = Read-Host "Enter a URL such as https://foobar.com"
}
Catch
{
    Write-Host "URL requires http:// or https:// prefix e.g. https://cnn.com"
}


$webClient = New-Object Net.WebClient
[string]$results = $webClient.DownloadString($sourceUrl)


[string]$cleanResults = htmlStrip $results


$body = 
[ordered]@{"documents" = 
    @{ "language" = "en"; "id" = $sourceUrl; "text" = $cleanResults }
    }

#>

$body = [ordered]@{
    "documents" = 
    @(
        @{ "language" = "en"; "id" = $sourceUrl; "text" = $cleanResults }
    )
}

$jsonBody = $body | ConvertTo-Json

#Begin Text Analytics API Call with Invoke-RestMethod wrapper
#[string]$apiUrl = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases"
[string]$apiKey = "REDACTED"


$headers = @{ "Ocp-Apim-Subscription-Key" = $apiKey }

$analyticsResults = Invoke-RestMethod -Method Post -Uri $apiUrl -Headers $headers -Body $jsonBody -ContentType "application/json"  -ErrorAction Stop

Write-Host $analyticsResults

Write-Host $jsonBody

1 个答案:

答案 0 :(得分:2)

您在请求的text属性中输入的数据可能无效 我尝试使用GitHub上TypeScript repo的README.md的修复URL修复脚本并且它可以工作。

您的脚本(略有缩短)

$sourceUrl = 'https://raw.githubusercontent.com/Microsoft/TypeScript/master/README.md'

$webClient = New-Object Net.WebClient
$results = $webClient.DownloadString($sourceUrl)

$body = [ordered]@{
    "documents" = 
    @(
        @{ "language" = "en"; "id" = $sourceUrl; "text" = $results }
    )
}

$jsonBody = $body | ConvertTo-Json

$apiUrl = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases"
$apiKey = "..."

$headers = @{ "Ocp-Apim-Subscription-Key" = $apiKey }

$analyticsResults = Invoke-RestMethod -Method Post -Uri $apiUrl -Headers $headers -Body $jsonBody -ContentType "application/json"  -ErrorAction Stop
$analyticsResults.documents.keyPhrases

<强>结果

TypeScript compiler
gulp tests
g typescript
TypeScript source
built compiler
TypeScript users
g gulp
TypeScript directory
cd TypeScript
gulp baseline
gulp lint
gulp local
gulp clean
gulp runtests-browser
gulp LKG
Install Gulp tools
...