Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

Issues with PowerShell generated JSON and CloudFlares API

I am trying to write some PowerShell to update an 'A' record on my Cloudflare account. The code looks like the following:

##Configure headers
$Bearer = "Bearer " + $cloudflareAPIToken
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization",$Bearer)

##Configure Payload
$Body = @{
    type = 'A'
    Name = 'homepc'
    Content = '8.8.8.8'
    ttl = 1}

$Jsonbody = $Body | ConvertTo-Json -Compress

Invoke-RestMethod -Method PUT "https://api.cloudflare.com/client/v4/zones/$DNSZoneID/dns_records/$ARecordID"  -Headers $Headers -Body -$Jsonbody -ContentType 'application/json'

And I am getting the error

Invoke-RestMethod: {"result":null,"success":false,"errors":[{"code":9207,"message":"Content-type must be application/json."}],"messages":[]}

My json payload looks like this

PS C:UsersFrank> $Jsonbody

{"type":"A","Name":"homepc","ttl":1,"Content":"8.8.8.8"}

If I cut and paste this payload into Postman then it works. Bellow is the code generated by Postman. This works

curl --location --request PUT 'https://api.cloudflare.com/client/v4/zones/6b5e4cf4634bc20cebc1cd96072c/dns_records/4cb90f1dabfcc63a97055234520' 
--header 'Authorization: Bearer zHl3LhnQzRyw1_' 
--header 'Content-Type: application/json' 
--data-raw '{"type":"A","Name":"homepc","Content":"8.8.8.8","ttl":1}'

Can anyone help me get to the bottom of this?

Thank in advance

Frank

question from:https://stackoverflow.com/questions/65937681/issues-with-powershell-generated-json-and-cloudflares-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't use CloudFlare but from the error message it looks like you are missing the Content-Type header. Try adding this line:

$Headers.Add('Content-Type', 'application/json')

Edit: The header isn't needed as it was specified using -ContentType parameter to Invoke-RestMethod. On closer inspection of the command line the parameter -Body -$Jsonbody has an erroneous - in front of the JSON body variable which made the string that was sent -{....}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...