首页 > 代码库 > 使用 HTTP
使用 HTTP
Web 使用超文本传输协议(Hypertext Transfer Protocol,HTTP)通信,通常用 web 浏览器,但是,出于某些原因,也可能想用脚本或程序中发出 web 请求,例如,通过 RSS 或 Atom feeds 收集站点内容。
生成 HTTP 请求,需要用 System.Net.WebRequest 类的静态方法 Create。它创建 WebRequest 对象,表示对统一资源定位器(URL,用于唯一标识网络上资源的地址)的请求,URL 被传递给 Create 方法;然后,使用 GetResponse 方法获得服务器对这个请求的响应,用 System.Net.WebResponse 类表示。
下面的例子(清单 11-3)演示了调用 BBC 站点上的 RSS。这个例子的核心是函数 getUrlAsXml,它检索来自 URL 的数据,并把数据加载到 XmlDocument;其余部分是对数据的后期处理,即,在控制台上显示每一项的标题,用户可以选择某一项来显示。
清单 11-3. 使用 HTTP
open System
open System.Diagnostics
open System.Net
open System.Xml
///makes a http request to the given url
let getUrlAsXml (url: string) =
let request = WebRequest.Create(url)
let response = request.GetResponse()
let stream = response.GetResponseStream()
let xml = new XmlDocument()
xml.Load(stream)
xml
///the url we interested in
let url = "http://feeds.bbci.co.uk/news/rss.xml"
///main application function
let main() =
// read the rss fead
let xml = getUrlAsXml url
// write out the tiles of all the news items
let nodes = xml.SelectNodes("/rss/channel/item/title")
for i in 0 .. (nodes.Count - 1) do
printf "%i.%s\r\n" (i+ 1) (nodes.[i].InnerText)
// read the number the user wants from the console
let item = int(Console.ReadLine())
// find the new url
let newUrl =
let xpath = sprintf "/rss/channel/item[%i]/link" item
let node = xml.SelectSingleNode(xpath)
node.InnerText
// start the url using the shell, this automaticall opens
// the default browser
let procStart = new ProcessStartInfo(UseShellExecute =true,
FileName= newUrl)
let proc = new Process(StartInfo = procStart)
proc.Start() |> ignore
do main()
[
1、需要引用 System.Xml.dll
2、url 要改成:
let url = "http://feeds.bbci.co.uk/news/rss.xml"
]
这个结果是写作时的,实际运行会有变化:
1. Five-step check for nano safety
2. Neanderthal DNA secrets unlocked
3. Stem cells ‘treat muscle disease‘
4. World Cup site threat to swallows
5. Clues to pandemic bird flu found
6. Mice star as Olympic food tasters
7. Climate bill sets carbon target
8. Physics promises wireless power
9. Heart ‘can carry out own repairs‘
10. Average European ‘is overweight‘
11. Contact lost with Mars spacecraft
12. Air guitar T-shirt rocks for real
13. Chocolate ‘cuts blood clot risk‘
14. Case for trawl ban ‘overwhelming‘
15. UN chief issues climate warning
16. Japanese begin annual whale hunt
17. Roman ship thrills archaeologists
18. Study hopeful for world‘s forests