使用 POST 方法的 HttpWebRequest 的 VB.net 替代方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18900458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:08:13  来源:igfitidea点击:

VB.net alternative way of HttpWebRequest using POST method

vb.netposthttpwebrequesthttpwebresponse

提问by Marc Intes

Here is my code using HttpWebRequest to automatically fill-up a web form and submits it.

这是我使用 HttpWebRequest 自动填写 Web 表单并提交的代码。

            Dim cweb As String = "http://www.yellowpages.com/novato-ca/mip/creative-memories-consultant-senior-director-461725587/send_email?lid=171673036"
            Dim POST As String = "&email%5Bto_address%[email protected]&email%5Bfrom_name%5D=Test Name&email%5Bfrom_address%[email protected]&email%5Bnote%5D=Hello There"       

            Dim request As HttpWebRequest
            Dim response As HttpWebResponse

            request = CType(WebRequest.Create(cweb), HttpWebRequest)
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36"
            request.AllowAutoRedirect = True
            request.ContentType = "application/x-www-form-urlencoded"
            request.ContentLength = POST.Length
            request.Method = "POST"
            request.KeepAlive = True

            Dim requestStream As Stream = request.GetRequestStream()
            Dim postBytes As Byte() = Encoding.ASCII.GetBytes(POST)
            requestStream.Write(postBytes, 0, postBytes.Length)
            requestStream.Close()

            response = CType(request.GetResponse(), HttpWebResponse)
            response.Close()

In this code I have used yellowpages' mailing form as an example. Yes it does let me fill-up and submit but I want another alternatives. Is there any other alternatives aside from WebClient as i have tried it already that is able to send POST requests? I have read about topics regarding System.Net.Sockets that it is able to send POST request, but I don't know where to start. Any tips will be gladly accepted. I really find HttpWebRequest and WebClient abit slow in sending POST requests.

在这段代码中,我使用了 Yellowpages 的邮件表单作为示例。是的,它确实让我填写并提交,但我想要另一种选择。除了 WebClient 之外还有其他替代方法吗,因为我已经尝试过它可以发送 POST 请求?我已经阅读了有关 System.Net.Sockets 的主题,它能够发送 POST 请求,但我不知道从哪里开始。任何提示将被欣然接受。我真的发现 HttpWebRequest 和 WebClient 在发送 POST 请求时有点慢。

回答by Minh

Hi you can try to use this way

嗨,您可以尝试使用这种方式

Using sendto As New Net.WebClient
    Dim param As New Specialized.NameValueCollection
    param.Add("param1", "value1")
    param.Add("param2", "value2")
    Dim response_bytes = sendto.UploadValues(yourUrl, "POST", param)
    Dim response_body = (New Text.UTF8Encoding).GetString(response_bytes)
End Using