使用 HTTP

使用HTTP

 

 

网站使用超文本传输协议(HTTP)进行通信,通常用网站浏览器,但是,你可能想出于几个原因,从脚本或者程序发出网站请求,例如,通过RSS 或者 Atom feeds汇集站点内容。

为了发出HTTP 请求,使用 System.Net.WebRequest 类中的 Create中静态方法,它创建了 WebRequest 对象,表示对统一资源定位符 (URL,在网络上唯一表示资源的地址)的请求,传递给 Create 方法。然后,使用GetResponse 方法得到服务器对你请求的应答,通过 System.Net.WebResponse 类表示。

下面的示例(清单 10-3)演示了调用 BBC网站的 RSS。这个示例的核心是 getUrlAsXml函数,它从 URL 中读取数据,并把数据加载到XmlDocument。示例的其余部分还演示了对数据进行后处理的种类,这里,在控制台上显示每一项的标题,用户可以选择显示的项。

 

清单10-3. 使用 HTTP

 

#light

 

open System.Diagnostics

open System.Net

open System.Xml

 

let getUrlAsXml (url :string) =

    let request = WebRequest.Create(url)

    let response = request.GetResponse()

    let stream = response.GetResponseStream()

    let xml = new XmlDocument()

    xml.Load(newXmlTextReader(stream))

    xml

//leturl ="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/sci/tech/rss.xml"

let url = "http://feeds.bbci.co.uk/news/uk/rss.xml"

let xml = getUrlAsXmlurl

let mutable i = 1

for node in xml.SelectNodes("/rss/channel/item/title") do

    printf "%i.%s\r\n" inode.InnerText

    i <- i + 1

//letitem = read_int()

let item =System.Console.ReadLine() |> System.Int32.Parse

let newUrl =

    let xpath = sprintf "/rss/channel/item[%i]/link" item

    let node = xml.SelectSingleNode(xpath)

    node.InnerText

let proc = new Process()

proc.StartInfo.UseShellExecute<- true

proc.StartInfo.FileName<- newUrl

proc.Start()|> ignore

 

    在写作本书时,这个示例的运行结果如下(你的结果可能不同):

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值