Submitting HTTP POST requests from PowerShell
After reading the topic Quotes from forismatic.com in the console (or do-it-yourself fortune) out of curiosity, I wanted to repeat the same thing on PowerShell. Here's what happened.
Below explanations and usage example.
The function returns an XML object quote. Use like this:
Small notes:
From my point of view, the most interesting thing here is the conversion to XML. The result is an object with which you can work with standard PowerShell methods, for example,
Returns a collection of xml elements of the type: Which can be filtered, for example like this:
function get-random-quote()
{
$apiUrl = 'http://www.forismatic.com/api/1.0/'
$client = new-object System.Net.WebClient
$client.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
$client.Encoding = [System.Text.Encoding]::UTF8
[xml]$quote = $client.UploadString($apiUrl, 'method=getQuote&format=xml' )
$quote.forismatic.quote
}
Below explanations and usage example.
The function returns an XML object quote. Use like this:
PS C:\Windows\system32> $quote = get-random-quote
______________________________________________________________________________________________________________________________________________________________________
PS C:\Windows\system32> $quote
quoteText quoteAuthor senderName senderLink
--------- ----------- ---------- ----------
Каждый миг наслаждения — это дар богов. Клод Адриан Гельвеций
______________________________________________________________________________________________________________________________________________________________________
PS C:\Windows\system32> $quote.quoteAuthor
Клод Адриан Гельвеций
Small notes:
- Create a .Net WebClient Object
- We configure it by writing headers and encoding
- We call HTTP POST (if you use UploadString with three parameters, you can set the method)
- Convert the resulting string to XML
- Tear out a quote from a string
From my point of view, the most interesting thing here is the conversion to XML. The result is an object with which you can work with standard PowerShell methods, for example,
$client = new-object System.Net.WebClient
$client.Encoding = [System.Text.Encoding]::UTF8
[xml]$habr = $client.DownloadString('http://habrahabr.ru/rss/9c1806bb61d9b6612943104ddbf830d9/')
$habr.rss.channel.item
Returns a collection of xml elements of the type: Which can be filtered, for example like this:
title : title
guid : guid
link : habrahabr.ru/blogs/lenta/92187
description : description
pubDate : Tue, 27 Apr 2010 15:44:41 GMT
author : Mithgol
category : {военная техника, крылатые ракеты, Бирюза, Новатор...}
title : title
guid : guid
link : habrahabr.ru/blogs/startup/92152
description : description
pubDate : Tue, 27 Apr 2010 15:23:21 GMT
author : AynurEntre
category : {стартапы, монетизация, бизнес-модели, бизнес...}
....
$habr.rss.channel.item | where { $_.author -eq 'mithgol' } | select link, category