HTTP Get Request Using VBA in OSX Excel

前端 未结 2 1575
灰色年华
灰色年华 2021-02-10 09:16

I\'m writing a very simple macro that needs to make an HTTP GET request to a server and the response is not important (it initiates a process on the server). The HTTP GET does N

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-10 09:54

    Here is a piece of code that supports both OSX and Windows. I would credit the authors of this because I certainly didnt write this from scratch but I have lost track of where it all came from:

    #If Win32 Then
    
    Function getHTTP(URL As String, sQuery As String) As String
        Dim strResult As String
        Dim objHTTP As Object
        Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
        objHTTP.Open "GET", URL & "?" & sQuery, False
        objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
        objHTTP.send("")
        strResult = objHTTP.responseText
        getHTTP = strResult
    End Function
    
    
    #Else
    
    
    Option Explicit
    ' execShell() function courtesy of Robert Knight via StackOverflow
    ' http://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac
    Private Declare Function popen Lib "libc.dylib" (ByVal command As String, ByVal mode As String) As Long
    Private Declare Function pclose Lib "libc.dylib" (ByVal file As Long) As Long
    Private Declare Function fread Lib "libc.dylib" (ByVal outStr As String, ByVal size As Long, ByVal items As Long, ByVal stream As Long) As Long
    Private Declare Function feof Lib "libc.dylib" (ByVal file As Long) As Long
    
    
    Function execShell(command As String, Optional ByRef exitCode As Long) As String
    Dim file As Long
    file = popen(command, "r")
    If file = 0 Then
    Exit Function
    End If
    While feof(file) = 0
    Dim chunk As String
    Dim read As Long
    chunk = Space(50)
    read = fread(chunk, 1, Len(chunk) - 1, file)
    If read > 0 Then
    chunk = Left$(chunk, read)
    execShell = execShell & chunk
    End If
    Wend
    exitCode = pclose(file)
    End Function
    
    
    Function getHTTP(sUrl As String, sQuery As String) As String
        Dim sCmd As String
        Dim sResult As String
        Dim lExitCode As Long
        sCmd = "curl --get -d """ & sQuery & """" & " " & sUrl
        sResult = execShell(sCmd, lExitCode)
        ' ToDo check lExitCode
        getHTTP = sResult
    End Function
    
    #End If
    

提交回复
热议问题