HttpWebRequest和响应问题

时间:2011-02-12 07:07:52

标签: vb.net httpwebrequest

所以我有这个用于HTTPwebrequests的类。在我的程序的这个例子中,我发布了一些数据和cookie。现在是真正奇怪的部分。我使用fiddler来嗅探标题并监控我的程序在测试中的流量。如果fiddler打开,这个功能就可以了。如果fidler在我发布任何数据时关闭,则操作超时。它总是这样做。不管我做什么。当我沮丧地拔出头发时,任何人都可以对此有所了解。

    Public Function Send(ByVal URL As String, _
    Optional ByVal PostData As String = "", _
    Optional ByVal Method As HTTPMethod = HTTPMethod.HTTP_GET, _
    Optional ByVal ContentType As String = "", Optional ByVal Refer As String = "")

    Dim Request As HttpWebRequest = WebRequest.Create(URL)
    Dim Response As HttpWebResponse
    System.Net.ServicePointManager.Expect100Continue = False
    Dim SW As StreamWriter
    Dim SR As StreamReader
    Dim ResponseData As String
    Dim a As New CookieContainer()
    ' Request.Proxy = New WebProxy("173.234.250.164", 3128)
    ' Prepare Request Object
    Request.Method = Method.ToString().Substring(5)
    Request.CookieContainer = a
    ' Set form/post content-type if necessary
    If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
        ContentType = "application/x-www-form-urlencoded"
    End If


    'Set User Agent
    Request.UserAgent = ("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB6.6)")

    'Set Refer
    If (Refer <> "") Then
        Request.Referer = Refer
    End If


    ' Set Content-Type
    If (ContentType <> "") Then
        Request.ContentType = ContentType
        Request.ContentLength = PostData.Length
    End If

    'Set Cookie If Given
    If (Cookie <> "") Then
        Request.Headers.Add("cookie", Cookie)
    End If


    ' Send Request, If Request
    If (Method = HTTPMethod.HTTP_POST) Then
        Try
            Debug.Print("Inside Post")
            SW = New StreamWriter(Request.GetRequestStream())
            SW.Write(PostData)
            Debug.Print("Wrote Post Data")
        Catch Ex As Exception
            Throw Ex
        Finally
            SW.Close()
        End Try
    End If

    ' Receive Response
    Try
        Response = Request.GetResponse()
        For Each cook As Cookie In Response.Cookies
            Cookie = Cookie & cook.ToString() & ";"
        Next
        Debug.Print(Cookie)

        SR = New StreamReader(Response.GetResponseStream())
        ResponseData = SR.ReadToEnd()
    Catch Wex As System.Net.WebException
        SR = New StreamReader(Wex.Response.GetResponseStream())
        ResponseData = SR.ReadToEnd()
        Throw New Exception(ResponseData)
    Finally
        SR.Close()
    End Try

    Return ResponseData


End Function

1 个答案:

答案 0 :(得分:0)

你永远不会处置HttpWebResponse - 这意味着连接将保持打开状态。您应该为Using使用Response语句。 (我还建议您尽可能晚地声明变量,而不是在方法顶部声明所有内容......并且在任何地方使用Using语句而不是在Finally块中关闭内容

请注意,当您可能未设置时,您还会在finally块中关闭SR - 如果抛出了您未预料到的某些异常,则您尝试关闭SR可能会抛出{ {1}}。就个人而言,我会分别对待两个StreamReader(一个在成功案例中,一个在失败案例中)。