1

我的 VB6 如何形成 POST 2 vars,从 URL 中提取结果,然后将 VB6 var 分配给结果?

我需要有人向我展示非常基本的 VB6 示例代码或指出我正确的方向。这是最简单的形式——在最终产品中,PHP 变量将写入 MySQL,但这不是我需要帮助的。

我有一个接受 2 个参数的简单 PHP 页面:

test.php?var1=secret&var2=pass

这是我非常简单的 PHP 代码

<?php

$var1 = $_GET['var1'];
$var2 = $_GET['var2'];

$varAcc = "ACCEPTED";
$varDen = "DENIED";

if ($var1 === "secret" && $var2 === "pass")
  {
   echo $varAcc;
  }
else
  {
   echo $varDen;
  }
?>

这背后的逻辑是使用“userName”、“passWord”和“hardWareID”进行 VB6 登录,并发送一个哈希值。哈希将根据 MySQL 检查它是否存在,并返回 YES 或 NO 进行访问,他们的帐户还剩下多少天,以及一些其他详细信息,如 FULL NAME、ACCOUNT INFO 等。

(不..我不想使用 XML,只是想我会把它放在那里..只需 POST & Receive 到 vars)

谢谢你...

4

2 回答 2

5

VB 表单没有任何用于发送 HTTP 请求的内置机制。有些人可能会建议您使用 Internet 传输控制。但是,VB UserControl 有一个 HTTP 机制,您可以在不需要第三方控件的情况下使用它,假设您使用 GET 方法,并使用查询字符串来传递您的参数。如果必须使用 POST,则必须使用 Internet 传输控制。

创建一个引用“Microsoft Scripting Runtime”的 VB 项目(参见菜单 Project=>References)。添加一个用户控件。称之为“HttpService”。设置 InvisibleAtRuntime=True。将以下代码添加到 UserControl:

Option Explicit

Private Const m_ksProperty_Default              As String = ""

Private m_sHost                                 As String
Private m_nPort                                 As Long
Private m_sPath                                 As String
Private m_dctQueryStringParameters              As Scripting.Dictionary

Private m_sOutput                               As String

' Ensure that all parts of the query string are deleted.
Public Sub ClearQueryString()

    Set m_dctQueryStringParameters = New Scripting.Dictionary

End Sub

' Executes "GET" method for URL.
Public Function Get_() As String

    ' Read in data from URL. UserControl_AsyncReadComplete will fire when finished.
    UserControl.AsyncRead "http://" & m_sHost & ":" & CStr(m_nPort) & "" & m_sPath & "?" & GetQueryString(), vbAsyncTypeByteArray, m_ksProperty_Default, vbAsyncReadSynchronousDownload

    ' Return the contents of the buffer.
    Get_ = m_sOutput

    ' Clear down state.
    m_sOutput = vbNullString

End Function

' Returns query string based on dictionary.
Private Function GetQueryString() As String

    Dim vName                                   As Variant
    Dim sQueryString                            As String

    For Each vName In m_dctQueryStringParameters
        sQueryString = sQueryString & CStr(vName) & "=" & m_dctQueryStringParameters.Item(vName) & "&"
    Next vName

    GetQueryString = Left$(sQueryString, Len(sQueryString) - 1)

End Function

' Sets the remote host.
Public Property Let Host(ByVal the_sValue As String)

    m_sHost = the_sValue

End Property

' Sets the directory and filename part of the URL.
Public Property Let Path(ByVal the_sValue As String)

    m_sPath = the_sValue

End Property

' Sets the port number for this request.
Public Property Let Port(ByVal the_nValue As Long)

    m_nPort = the_nValue

End Property

' Sets a name/value pair in the query string. Supports duplicate names.
Public Property Let QueryStringParameter(ByVal the_sName As String, ByVal the_sValue As String)

    m_dctQueryStringParameters.Item(the_sName) = the_sValue

End Property

' Fired when the download is complete.
Private Sub UserControl_AsyncReadComplete(AsyncProp As AsyncProperty)

    ' Gets the data from the internet transfer.
    m_sOutput = StrConv(AsyncProp.Value, vbUnicode)

End Sub

Private Sub UserControl_Initialize()

    ' Initialises the scripting dictionary.
    Set m_dctQueryStringParameters = New Scripting.Dictionary

End Sub

要使用此 UserControl,请将其添加到您的表单中。称之为“HttpService”。添加一个名为“txtOutput”的文本框来测试表单上的以下代码:

HttpService.Host = "localhost"
HttpService.Port = 80
HttpService.Path = "/test.php"
HttpService.QueryStringParameter("var1") = "secret"
HttpService.QueryStringParameter("var2") = "pass"

txtOutput.Text = HttpService.Get_
于 2013-04-02T08:12:11.293 回答
1

如果必须使用 POST,则必须使用 Internet 传输控制。在 VB6 IDE 中,按 CTL-T,然后选择“Microsoft Internet Transfer Control 6.0”。按确定。

将控件的实例添加到窗体。称之为“Inet”。向窗体添加一个名为“cmdPost”的命令按钮。添加对“Microsoft Scripting Runtime”的引用(参见菜单 Project=>References)。

将以下代码添加到您的表单中:

Option Explicit

Private Declare Function InternetCanonicalizeUrl Lib "Wininet.dll" Alias "InternetCanonicalizeUrlW" ( _
    ByVal lpszUrl As Long, _
    ByVal lpszBuffer As Long, _
    ByRef lpdwBufferLength As Long, _
    ByVal dwFlags As Long _
) As Long

Private m_sData                         As String
Private m_nDataReceived                 As Long
Private m_bPostActive                   As Boolean
Private m_bDataReceived                 As Boolean
Private m_bError                        As Boolean          ' For error handling.
Private m_bDisconnected                 As Boolean

Private Sub cmdPost_Click()

    Dim dctParameters                   As Scripting.Dictionary

    txtOutput.Text = vbNullString

    m_sData = vbNullString
    Set dctParameters = New Scripting.Dictionary

    dctParameters.Add "var1", "secret"
    dctParameters.Add "var2", "pass"

    txtOutput.Text = Post("http://localhost:80/test.php", dctParameters)

End Sub

' Returns post data string based on dictionary.
Private Function GetPostDataString(ByRef the_dctParameters As Scripting.Dictionary) As String

    Dim vName                                   As Variant
    Dim sPostDataString                         As String

    For Each vName In the_dctParameters
        sPostDataString = sPostDataString & UrlEncode(CStr(vName)) & "=" & UrlEncode(CStr(the_dctParameters.Item(vName))) & "&"
    Next vName

    GetPostDataString = Left$(sPostDataString, Len(sPostDataString) - 1)

End Function

Private Sub Inet_StateChanged(ByVal State As Integer)

    ' Ignore state change if we are outside the Post function.
    If m_bPostActive Then

        Select Case State
        Case StateConstants.icResponseReceived
            ReceiveData False
        Case StateConstants.icResponseCompleted
            ReceiveData True
        Case StateConstants.icDisconnected
            m_bDisconnected = True
        Case StateConstants.icError
            m_bError = True
        End Select

    End If

End Sub

' Synchronous Post function.
Private Function Post(ByRef the_sURL As String, ByRef the_dctParameters As Scripting.Dictionary)

    Dim sPostData                               As String
    Dim sHeaders                                As String

    ' Flag that we are in the middle of this function.
    m_bPostActive = True

    ' Create a string containing the POST parameters.
    sPostData = GetPostDataString(the_dctParameters)

    ' Create a headers string to allow POST.
    sHeaders = _
        "Content-Type: application/x-www-form-urlencoded" & vbNewLine & _
        "Content-Length: " & CStr(Len(sPostData)) & vbNewLine & _
        "Connection: Keep-Alive" & vbNewLine & _
        "Cache-Control: no-cache" & vbNewLine

    Inet.Execute the_sURL, "POST", GetPostDataString(the_dctParameters), sHeaders

    ' Allow Inet events to fire.
    Do
        DoEvents
    Loop Until m_bDataReceived Or m_bDisconnected

    If m_bDataReceived Then
        Post = m_sData
    End If

    ' Clear all state flags to defaults.
    m_bDataReceived = False
    m_bDisconnected = False
    m_bError = False
    m_sData = vbNullString
    m_nDataReceived = 0

    ' Flag that we have exited this function.
    m_bPostActive = False

End Function

' Receive as much data as we can.
' <the_bCompleted> should be True if the response is completed i.e. all data is available.
Private Sub ReceiveData(ByVal the_bCompleted As Boolean)

    Const knBufferSize                  As Long = 1024
    Dim nContentLength                  As Long
    Dim sContentType                    As String
    Dim sChunk                          As String
    Dim nChunkSize                      As Long

    ' If we haven't yet created our buffer, do so now, based on the size of the incoming data.
    If m_nDataReceived = 0 Then
        nContentLength = CLng(Inet.GetHeader("Content-length"))
        m_sData = Space$(nContentLength)

        ' You might want to do a check on the content type here, and if it is wrong, cancel the request with Inet.Cancel .
        sContentType = Inet.GetHeader("Content-type")
    End If

    ' Retrieve data until we have all the data.
    Do Until m_nDataReceived = Len(m_sData)

        ' If called when not all data has been received, then exit function if it is currently executing.
        If Not the_bCompleted Then
            If Inet.StillExecuting Then
                Debug.Print "Exiting"
                Exit Sub
            End If
        End If

        ' Get a chunk, copy it into the output buffer, and increment the amount of data received.
        sChunk = Inet.GetChunk(knBufferSize, DataTypeConstants.icString)
        nChunkSize = Len(sChunk)
        Mid$(m_sData, m_nDataReceived + 1, nChunkSize) = sChunk
        m_nDataReceived = m_nDataReceived + nChunkSize

    Loop

    ' Flag that all data has been retrieved.
    m_bDataReceived = True

End Sub

' Encode the URL data.
Private Function UrlEncode(ByVal the_sURLData As String) As String

    Dim nBufferLen                      As Long
    Dim sBuffer                         As String

    ' Only exception - encode spaces as "+".
    the_sURLData = Replace$(the_sURLData, " ", "+")

    ' Try to #-encode the string.
    ' Reserve a buffer. Maximum size is 3 chars for every 1 char in the input string.
    nBufferLen = Len(the_sURLData) * 3
    sBuffer = Space$(nBufferLen)
    If InternetCanonicalizeUrl(StrPtr(the_sURLData), StrPtr(sBuffer), nBufferLen, 0&) Then
        UrlEncode = Left$(sBuffer, nBufferLen)
    Else
        UrlEncode = the_sURLData
    End If

End Function
于 2013-04-03T13:27:36.887 回答