Visual basic 以编程方式将用户名和密码传递给 https url 以使 webbrowser 显示网页并从网页下载

Visual basic programmatically pass username and password to https url to make webbrowser display webpage and also download from webpage

使用普通 HTTP,我可以下载上传并导航到路由器,但是当路由器使用 HTTPS 时,我找不到任何代码来执行这些操作。

要下载我使用这个:

Try
    My.Computer.Network.DownloadFile("http://" & "180.29.74.70" & "/cgi-bin/log.cgi", "C:\Users\ssb\Desktop\randomword.txt", "username", "password")
    WebBrowser1.Refresh()
Catch ex As Exception
    MessageBox.Show("Router not sufficient for operation Return for Inspection cannot download log file")
End Try

要上传文件,我使用这个:

  My.Computer.Network.UploadFile("C:\Users\ssb\Desktop\tomtn.txt", "http://" & "180.29.74.70" & "/cgi-bin/updateconfig.cgi", "username", "password")

要导航到 HTTP 上的网页,我使用这个:

WebBrowser1.Navigate("https://username:password@180.29.74.70 ")

但是当我使用 HTTPS 时:

WebBrowser1.Navigate("https://username:password@180.29.74.70 ")

我收到此安全警报:

然后我单击“是”并转到该页面——但我需要代码来绕过这些安全问题。

尽管它们关系松散,但您在这里提出了两个不同的问题。

  1. 为什么我使用 WebBrowser 控件通过 HTTPS 加载页面时调用失败?
  2. 为什么我使用DownloadFile()方式通过HTTPS下载文件时调用失败?

首先,您需要排除代码失败的可能性。使用已知可以正常工作的 public HTTPS URL 尝试上述两项任务。

如果您发现问题的根源是您的私有 URL,您可能需要考虑是否要忽略 WebBrowser 控件中的 SSL 错误。

您可以使用来自 this blog post:

的(未经测试,已翻译为 VB)代码执行此操作
Partial Public Class Form1
  Inherits Form

  Private WithEvents WebBrowser As New WebBrowser

  Private Sub WebBrowser_DocumentCompleted(Sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
    If e.Url.ToString() = "about:blank" Then
      'create a certificate mismatch
      WebBrowser.Navigate("https://74.125.225.229/")
    End If
  End Sub
End Class



<Guid("6D5140C1-7436-11CE-8034-00AA006009FA")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
<ComImport>
Public Interface UCOMIServiceProvider
  <PreserveSig>
  Function QueryService(<[In]> ByRef guidService As Guid, <[In]> ByRef riid As Guid, <Out> ByRef ppvObject As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface



<ComImport>
<ComVisible(True)>
<Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IWindowForBindingUI
  <PreserveSig>
  Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface



<ComImport>
<ComVisible(True)>
<Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IHttpSecurity
  'derived from IWindowForBindingUI
  <PreserveSig>
  Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
  <PreserveSig>
  Function OnSecurityProblem(<[In], MarshalAs(UnmanagedType.U4)> dwProblem As UInteger) As Integer
End Interface



Public Class MyWebBrowser
  Inherits WebBrowser
  Public Shared IID_IHttpSecurity As New Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")
  Public Shared IID_IWindowForBindingUI As New Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")
  Public Const S_OK As Integer = 0
  Public Const S_FALSE As Integer = 1
  Public Const E_NOINTERFACE As Integer = &H80004002
  Public Const RPC_E_RETRY As Integer = &H80010109



  Protected Overrides Function CreateWebBrowserSiteBase() As WebBrowserSiteBase
    Return New MyWebBrowserSite(Me)
  End Function



  Private Class MyWebBrowserSite
    Inherits WebBrowserSite

    Implements UCOMIServiceProvider
    Implements IHttpSecurity
    Implements IWindowForBindingUI

    Private myWebBrowser As MyWebBrowser



    Public Sub New(myWebBrowser As MyWebBrowser)
      MyBase.New(myWebBrowser)
      Me.myWebBrowser = myWebBrowser
    End Sub



    Public Function QueryService(ByRef guidService As Guid, ByRef riid As Guid, ByRef ppvObject As IntPtr) As Integer Implements UCOMIServiceProvider.QueryService
      If riid = IID_IHttpSecurity Then
        ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IHttpSecurity))
        Return S_OK
      End If
      If riid = IID_IWindowForBindingUI Then
        ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IWindowForBindingUI))
        Return S_OK
      End If
      ppvObject = IntPtr.Zero
      Return E_NOINTERFACE
    End Function



    Public Function GetWindow(ByRef rguidReason As Guid, ByRef phwnd As IntPtr) As Integer Implements IHttpSecurity.GetWindow, IWindowForBindingUI.GetWindow
      If rguidReason = IID_IHttpSecurity OrElse rguidReason = IID_IWindowForBindingUI Then
        phwnd = myWebBrowser.Handle
        Return S_OK
      Else
        phwnd = IntPtr.Zero
        Return S_FALSE
      End If
    End Function



    Public Function OnSecurityProblem(dwProblem As UInteger) As Integer Implements IHttpSecurity.OnSecurityProblem
      'ignore errors
      'undocumented return code, does not work on IE6
      Return S_OK
    End Function
  End Class
End Class

关于问题 #2:看来您可能混淆了 WebBrowserDownloadFile()。您可能已经发现,WebBrowser 控件不下载文件。但是,您可以使用 this technique:

模拟行为
Partial Public Class Form2
  Inherits Form

  Private Sub WebBrowser_Navigating(Sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser.Navigating
    Dim sFilePath As String
    Dim oClient As Net.WebClient

    ' This can be any conditional criteria you wish '
    If (e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".pdf")) Then
      SaveFileDialog.FileName = e.Url.Segments(e.Url.Segments.Length - 1)
      e.Cancel = True

      If SaveFileDialog.ShowDialog() = DialogResult.OK Then
        sFilePath = SaveFileDialog.FileName
        oClient = New Net.WebClient

        AddHandler oClient.DownloadFileCompleted, New AsyncCompletedEventHandler(AddressOf DownloadFileCompleted)

        oClient.DownloadFileAsync(e.Url, sFilePath)
      End If
    End If
  End Sub



  Private Sub DownloadFileCompleted(Sender As Object, e As AsyncCompletedEventArgs)
    MessageBox.Show("File downloaded")
  End Sub



  Private WithEvents SaveFileDialog As New SaveFileDialog
  Private WithEvents WebBrowser As New WebBrowser
End Class

无论如何,解决这个问题的第一步是弄清楚是您的代码还是私有 URL 导致了您的问题。

这里需要做的主要事情是以编程方式从 https url 下载文件,同时使用被安全证书问题阻止的用户名和密码

搜索2周后的解决方案是

要下载文件,您可以使用以下代码暂时禁用安全证书请求,然后在代码 运行 之后再次启用安全证书

你甚至不需要浏览器的第一个代码它会自动将文件保存到你的桌面

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'check if a simular file doesnt exists so you can create a new file and deletes the file if it exists
        If File.Exists("C:\pathtoyourfile\yourfilename.txt") Then
            File.Delete("C:\pathtoyourfile\yourfilename.txt")
        End If

        'Type this before your download or hhtps request
        'ByPass SSL Certificate Validation Checking
        System.Net.ServicePointManager.ServerCertificateValidationCallback =
  Function(se As Object,
  cert As System.Security.Cryptography.X509Certificates.X509Certificate,
  chain As System.Security.Cryptography.X509Certificates.X509Chain,
  sslerror As System.Net.Security.SslPolicyErrors) True

        'Call web application/web service with HTTPS URL here
        '=========================================================================================
        'ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
        Try
            My.Computer.Network.DownloadFile("https://176.53.78.22/filenameonserveryouwanttodownload", "C:\pathtoyourfile\yourfilename.txt", "Yourusername", "yourpassword")
            WebBrowser1.Refresh()
        Catch ex As Exception
            MessageBox.Show("message saying something didnt work")
            'exit sub if it worked
            Exit Sub
        End Try
        MessageBox.Show(" message saying it worked")
        '=========================================================================================
        'Restore SSL Certificate Validation Checking
        System.Net.ServicePointManager.ServerCertificateValidationCallback = Nothing
    End Sub

然后浏览到一个网址,将弹出以下代码并弹出安全弹出窗口,但 select 是的,浏览网页正常

WebBrowser1.Navigate("https://username:password@180.29.74.70 ")

如你所说:

[...] I need the code to bypass any security questions like these.

换句话说,您需要“自动接受自签名 SSL 证书”,所以在我看来这是一个重复的问题:VB .net Accept Self-Signed SSL certificate,这可能符合您的需要。

尤其是 slaks 答案:

In VB.Net, you need to write:

ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications