vb.net 教程 12-8 WebRequest 和 Webresponse 4-2 POST方式向网页发送数据

post的步骤比get要复杂,
1、将要发送的变量和值按照“变量1=值1&变量2=值2……”这样的方式写入文本
2、将文本按照网页编码转为字节数组
3、定义webrequest对象
4、设置webrequest对象的ContentLength属性为字节数组大小
5、指定webrequest对象发送数据流的类型,这里是"application/x-www-form-urlencoded",以后发送文件的时候会用到别的类型
6、指定webrequest对象方法为"POST"
7、获得请求的流(getrequeststream)
8、将字节数组写入流中,如果比较大的话,需要将字节数组分段写入
9、剩余的操作同前几节。。。
具体操作代码如下:

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim poststring As String = "txtname1=测试1&txtname2=测试2"
        Dim addr As String = txtform.Text
        Try
            Dim buffer() As Byte = Encoding.GetEncoding("gb2312").GetBytes(poststring)

            Dim myWebRequest As WebRequest = WebRequest.Create(addr)
            myWebRequest.ContentLength = buffer.Length
            myWebRequest.ContentType = "application/x-www-form-urlencoded"
            myWebRequest.Method = "POST"

            Dim mysendstream As Stream = myWebRequest.GetRequestStream

            mysendstream.Write(buffer, 0, buffer.Length)

            Dim myWebresponse As WebResponse = myWebRequest.GetResponse
            Dim myrecvstream As Stream = myWebresponse.GetResponseStream

            Dim singleReadCount As Integer = 10240
            Dim mybyte(singleReadCount - 1) As Byte
            Dim strpagecontent As String = ""


            Dim intreadl As Integer = 0
            Do
                intreadl = myrecvstream.Read(mybyte, 0, singleReadCount)
                strpagecontent &= Encoding.GetEncoding("gb2312").GetString(mybyte, 0, intreadl)
            Loop While intreadl > 0

            Console.WriteLine(strpagecontent)
            mysendstream.Close()
            myrecvstream.Close()
            myWebresponse.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

执行结果如下:

你会很吃惊地发现,不是我们需要的结果。
ok,把文本框中的showform1.asp更换为showform2.asp。这次看看:


这次成功了。
看来和asp代码中获得值的方法有关系。
在showform1中使用的是 request.querystring()方式
在showform2中使用的是 request.form()的方式
用哪一种,大家根据网页具体代码来吧。

由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看vb.net 教程 目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.Net学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值