如何使用Async Webrequest功能?

时间:2015-12-14 05:11:01

标签: vb.net

当前代码:

Public Sub Web1req()
Dim Req As HttpWebRequest
                    Req = CType(WebRequest.Create("http://something.org/"), HttpWebRequest)
                    Req.Method = "POST"
                    Req.ContentType = "application/x-www-form-urlencoded; charset=utf-8"
                    Req.CookieContainer = logincookie
                    Req.Timeout = 2000

        '<DO SOMETHING TO DELIVER [POSTDATA] AND ["FUNCTION" ARGUMENT] TO ASYNC PROCEDURE ABOVE> But how??


Dim result As IAsyncResult = CType(Req.BeginGetRequestStream(AddressOf GetRequestStreamCallback, Req), IAsyncResult)

end sub

 Private Sub GetResponseCallback(ByVal asynchronousResult As IAsyncResult)
 Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)
            Dim response As HttpWebResponse = CType(request.EndGetResponse(asynchronousResult), HttpWebResponse)

            Dim streamResponse As Stream = response.GetResponseStream()
            Dim streamRead As New StreamReader(streamResponse)
            Dim responseString As String = streamRead.ReadToEnd()

streamResponse.Close()
            streamRead.Close()
            response.Close()
End Sub

Private Sub GetRequestStreamCallback(ByVal asynchronousResult As IAsyncResult)
Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)

            Dim postStream As Stream = request.EndGetRequestStream(asynchronousResult)
            Dim postData As String = REQ1
            Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData)

            postStream.Write(byteArray, 0, postData.Length)
            postStream.Close()
 Dim result As IAsyncResult = CType(request.BeginGetResponse(AddressOf GetResponseCallback, request),  _
                IAsyncResult)
 End Sub

我使用它如下,

REQ1=postdatastring

MyThread = New System.Threading.Thread(AddressOf web1req)
                    MyThread.Name = "MyThread1"
                    MyThread.IsBackground = True
                    MyThread.Start()

问题是,如果我继续更改postdata字符串并多次快速发送,它将无法正常运行。

如何将其设为功能, 所以我可以使用下面的东西吗?

WebData = web1req("postDataString")

0 个答案:

没有答案