使用 HTTP Post

728 篇文章 1 订阅
86 篇文章 0 订阅

使用 HTTP Post

 

我们已经看过使用HTTP 协议检索数据的两种不同方法,下面,我们将学习如何使用上HTTP 进行更新。为了能够让客户端发送数据,HTTP协议提供了POST 动词,它把客户端发送数据作为 HTTP 请求体的一部分。

下一步是使用流行的社交网络工具推特进行状态更新,地址:http://twitter.com(见清单 11-5)。

 

清单 11-5 使用 HTTP POST 更新推特状态

 

open System

open System.Net

open System.Text

 

let postTweet username password tweet =

  //create a token to authenticate

  let(token: string) = username + ":" + password

  letuser = Convert.ToBase64String(Encoding.UTF8.GetBytes(token))

  //determine what we want to upload as a status

  letbytes = Encoding.ASCII.GetBytes("status=" + tweet)

  //connect with the update page

  letrequest =

    WebRequest.Create("http://twitter.com/statuses/update.xml",

                     Method = "POST",

                     ContentLength =Convert.ToInt64(bytes.Length),

                     ContentType ="application/x-www-form-urlencoded")

                     :?> HttpWebRequest

  request.ServicePoint.Expect100Continue<- false

  //set the authorisation levels

  request.Headers.Add("Authorization","Basic " + user)

 

  //set up the stream

  usereqStream = request.GetRequestStream()

  reqStream.Write(bytes,0, bytes.Length)

  reqStream.Close()

 

postTweet "you" "xxx""Test tweet from F# interactive"

 

用 HTTP POST 数据,与检索数据没有术大的不同。主要的差别在于,当创建WebRequest 时,有几个不同的属性是必须配置的,比如,要设置属性Method、ContentLength 和 ContentType;要想真正让用户能够更新他的状态,还需要在 HTTP 头中加上身份认证的令牌(authentication token):

 

// set the authorisation levels

request.Headers.Add("Authorization","Basic " + user)

 

最后,需要把数据写入请求流,这很简单,与写数据流是一回事:

 

use reqStream = request.GetRequestStream()

reqStream.Write(bytes, 0, bytes.Length)

reqStream.Close()

 

可能这个示例最有意义的地方在于它能运行在 F# 交互中。如果你是一个推特粉,可以在不离开编程环境的情况下,更新你的推特状态。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值