HttpWebRequest:使用“useUnsafeHeaderParsing = true”的post方法

时间:2016-02-10 01:28:01

标签: vb.net post cookies httpwebrequest

我正在尝试连接到第三方网站,然后获取源代码。
它对我来说效果很好,过了一段时间我再次尝试登录然后收到错误消息:
{”服务器提交了协议违规。 Section = ResponseStatusLine“}
在google上快速搜索后我发现我sholud要添加到“app.config”以下条目:<httpWebRequest useUnsafeHeaderParsing = true/>
之后它运作良好。但是,我将源代码视为guset,而不是“连接用户”。

我尝试了另一个不需要“UseUnsafeHeaderParsing = true”的网站,但效果很好。 它看起来像“UseUnsafeHeaderParsing = true”破坏性cookie?

*对不起我的英语,这不是我的母语。

这是我的代码:

Private siteCookies As New Net.CookieContainer()

    Function siteRequest(url As String, ByVal Method As String, Optional ByVal data As String = Nothing) As String
        Static soucrecode As String = Nothing
        Const UserAgent As String = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
        Try

            Dim Request As Net.HttpWebRequest = Net.WebRequest.Create(url)
            Request.Accept = "*/*"
            Request.Timeout = 10000
            Request.Method = Method
            Request.UserAgent = UserAgent
            Request.AllowAutoRedirect = True
            Request.CookieContainer = siteCookies
            If Request.Method = "POST" AndAlso data IsNot Nothing Then
                Dim postBytes() As Byte = New UTF8Encoding().GetBytes(data)
                Request.ContentType = "application/x-www-form-urlencoded"
                Request.ContentLength = postBytes.Length
                Request.GetRequestStream().Write(postBytes, 0, postBytes.Length)
            End If

            Dim Response As Net.HttpWebResponse = Request.GetResponse()
            soucrecode = New IO.StreamReader(Response.GetResponseStream).ReadToEnd()
            Response.Close()
        Catch e As Exception
         Console.WriteLine(e.Message)

        End Try
        Return soucrecode
    End Function

使用:

txtLoginSoucre.Text = siteRequest("http://www.SomeSite.com/login.php?do=login", "Post", "username=myUser&password=MyPass") ' Login to site
txtSoucre.Text siteRequest("http:  //www.SomeSite.com", "Get") 'Grab soucrecode

1 个答案:

答案 0 :(得分:0)

添加

Request.KeepAlive = False