【问题标题】:VB.NET HTTPS WEBREQUESTVB.NET HTTPS 网络请求
【发布时间】:2026-01-28 22:00:01
【问题描述】:

我有一个使用 httpwebrequest 发布文本文件的 VB.NET 代码。将 URL 从 http:// 更改为 https:// 后,代码将不再工作,并生成以下消息:“远程服务器返回错误:(407) 需要代理身份验证。”

请注意,我尝试使用 POSTMAN(在 google chrome 上)手动发布文件,它工作得很好,无需请求代理身份验证。为什么只有当我尝试使用 vb.net 代码发布我的文本文件时才会生成此错误消息,我该如何解决?

这是我的代码:

Imports System


Imports System.IO
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Configuration
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Net
Imports System.Threading
Imports System.Security.Cryptography.X509Certificates
Imports System.Net.Security
Module Module1

Sub Main()
    Dim dateTime As String = " "
    Dim createddate As String = " "
    Dim headerbytelength() As Byte
    Dim endboundlength() As Byte
    Dim e As String = "Test.txt"
    dateTime = DateAndTime.Now.ToString()
    createddate = DateAndTime.Now.ToString("yyyyMMdd_HHmmssfff")
    Dim strRequestURL = ConfigurationManager.AppSettings("strRequestURL").ToString()
    Dim strFilename = ConfigurationManager.AppSettings("Path") + e
    Dim request As HttpWebRequest = CType(WebRequest.Create(strRequestURL), HttpWebRequest)

    request.Method = "POST"
    CType(request, HttpWebRequest).UserAgent = ".NET Framework Example Client"
    Dim response As HttpWebResponse
    Dim JSONResponse As String = ""
    Dim writer As TextWriter = New StreamWriter(ConfigurationManager.AppSettings("LogPath"), True)
    writer.WriteLine("")
    writer.WriteLine("File name: " + e + "    Date/Time: " + createddate)
    writer.WriteLine("")

    Try
        System.Threading.Thread.Sleep(ConfigurationManager.AppSettings("Delay"))
        Dim boundary As String = IO.Path.GetRandomFileName
        Dim header As New System.Text.StringBuilder()
        header.AppendLine("--" & boundary)
        header.Append("Content-Disposition: form-data; name=""file"";")
        header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(strFilename))
        header.AppendLine()
        header.AppendLine("Content-Type: application/octet-stream")
        header.AppendLine()
        Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header.ToString)
        Dim endboundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" & boundary & "--" & vbNewLine)
        headerbytelength = System.Text.Encoding.UTF8.GetBytes(header.ToString)
        endboundlength = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" & boundary & "--" & vbNewLine)
        request.AllowAutoRedirect = True
        request.Timeout = -1
        request.KeepAlive = True
        request.AllowWriteStreamBuffering = False
        request.ContentType = "multipart/form-data; boundary=" & boundary
        'request.ContentLength = 0
        request.ContentLength = headerbytes.Length + New IO.FileInfo(strFilename).Length + endboundarybytes.Length

        Dim s As IO.Stream = request.GetRequestStream
        s.Write(headerbytes, 0, headerbytes.Length)
        Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(strFilename)
        s.Write(filebytes, 0, filebytes.Length)
        s.Write(endboundarybytes, 0, endboundarybytes.Length)
        s.Close()

        response = CType(request.GetResponse(), HttpWebResponse)
        Dim receiveStream As Stream = response.GetResponseStream
        Dim readStream As New StreamReader(receiveStream, Encoding.UTF8)

        Dim jResults As JObject = JObject.Parse(readStream.ReadToEnd)
        Dim results As List(Of JToken) = jResults.Children().ToList()
        For Each item As JProperty In results
            item.CreateReader()
            If item.Name = "message" Then
                writer.WriteLine(item.Value.ToString)
            End If
            If item.Name = "status" Then
                writer.WriteLine(item.Value.ToString)
            End If
            If item.Name = "errors" Then
                Dim i As Integer = 0
                Dim spl() As String = Split(item.Value.ToString, "],")
                Do Until i > spl.Length - 1
                    writer.WriteLine(spl(i))
                    i = i + 1
                Loop
            End If
        Next

        If File.Exists(strFilename) Then
            File.Move(strFilename, (ConfigurationManager.AppSettings("HistPath") + createddate + "__" + e).ToString())
            writer.WriteLine("BLU File " + e + " was moved to: " + ConfigurationManager.AppSettings("HistPath"))
        End If

        response.Close()
        readStream.Close()

    Catch ex As Exception
        If ex.Message = "The remote server returned an error: (401) Unauthorized." Then
            writer.WriteLine("BLU File " + e + " is empty")
            If File.Exists(strFilename) Then
                File.Move(strFilename, (ConfigurationManager.AppSettings("HistPath") + e).ToString())
                writer.WriteLine("BLU File " + e + " was moved to: " + ConfigurationManager.AppSettings("HistPath"))
            End If
        Else
            writer.WriteLine(ex.ToString)
        End If
    End Try
    writer.WriteLine("------------------------------------------------END------------------------------------------------")
    writer.Close()
End Sub
Public Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
    Return True
End Function

结束模块

【问题讨论】:

    标签: .net vb.net post proxy httpwebrequest


    【解决方案1】:

    可能需要抢先式身份验证。如果您不知道文档中的参数,我建议您安装像 fiddler 这样的应用程序。

    【讨论】: