码迷,mamicode.com
首页 > 其他好文 > 详细

使用 HTTP

时间:2014-05-22 23:02:45      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:des   style   c   tar   ext   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

使用 HTTP,布布扣,bubuko.com

使用 HTTP

标签:des   style   c   tar   ext   http   

原文地址:http://blog.csdn.net/hadstj/article/details/26485853

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!