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 教程 目录