将代理添加到HttpWebResponse

时间:2018-04-12 13:42:33

标签: vb.net httpwebresponse

使用WebRequest时,我可以添加系统默认代理和默认凭据,如此

WebRequest = System.Net.WebRequest.Create(URL)
WebRequest.Method = "GET"
WebRequest.ContentType = "application/x-www-form-urlencoded"
WebRequest.Headers.Add("...some headers here...")
WebRequest.Credentials = CRED
WebRequest.Proxy = System.Net.WebRequest.GetSystemWebProxy
WebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials


Public Shared Function MultipartFormDataPost(ByVal postUrl As String, ByVal postParameters As Dictionary(Of String, Object)) As HttpWebResponse
    Dim formDataBoundary As String = String.Format("----------{0:N}", Guid.NewGuid())
    Dim contentType As String = "multipart/form-data; boundary=" & formDataBoundary
    Dim formData As Byte() = GetMultipartFormData(postParameters, formDataBoundary)
    Return PostForm(postUrl, contentType, formData)
End Function

Private Shared Function PostForm(ByVal postUrl As String, ByVal contentType As String, ByVal formData As Byte()) As HttpWebResponse
    Dim request As HttpWebRequest = TryCast(WebRequest.Create(postUrl), HttpWebRequest)
    If request Is Nothing Then
        Throw New NullReferenceException("request is not a http request")
    End If
    request.Method = "POST"
    request.ContentType = contentType
    request.Credentials = CRED
    request.Headers.Add(EBC_TP_ZUGANG)
    request.CookieContainer = New CookieContainer()
    request.ContentLength = formData.Length
    request.Proxy = System.Net.WebRequest.GetSystemWebProxy
    request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
    Using requestStream As Stream = request.GetRequestStream()
        requestStream.Write(formData, 0, formData.Length)
        requestStream.Close()
    End Using

    Return TryCast(request.GetResponse(), HttpWebResponse)
End Function

当我需要将该代理添加到HttpWebResponse时,我该怎么办? 这是我的代码:

Dim postURL As String = "https://www.server.com/blabbla"
Dim webResponse As HttpWebResponse = clsFileUpload.MultipartFormDataPost(postURL, postParameters)
Dim responseReader As StreamReader = New StreamReader(webResponse.GetResponseStream())
Dim fullResponse As String = responseReader.ReadToEnd()
webResponse.Close()

0 个答案:

没有答案