VB6.0中调用接口API

注意XP环境与win7环境下的调用区分,XP下对接口https的调用会报错“接收格式异常”!!!


'返回接口地址返回结果字符串
Public Function GetResponse(sURL As String, Optional Method As String, Optional sBody As String) As String
    Dim aHttpRequest As Object
    
    Dim sMethod             As String
    Dim sResponse           As String
    
    If Method = "" Then
        sMethod = "POST"        '或者(GET)
    Else
        sMethod = Method
    End If
    
    Dim isXPSystem As Boolean

    If isXPSystem = True Then
        Set aHttpRequest = CreateObject("MSXML2.XMLHTTP")
        If sMethod = "GET" Then
            sBody = Replace(sBody, "?", "")
            sURL = sURL & "?" & sBody
        End If        
        
        '' 同步接收数据
        aHttpRequest.Open sMethod, sURL, False
        aHttpRequest.SetRequestHeader "Content-Length", Len(sBody)
        If InStr(1, sBody, "{") = 0 Then
            sBody = Replace(sBody, "?", "")
            aHttpRequest.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        Else
            aHttpRequest.SetRequestHeader "Content-Type", "application/json;charset=UTF-8"
        End If
        aHttpRequest.Send (sBody)
        
        Dim waitTimeOut, secondNumber
        waitTimeOut = 0
        secondNumber = 100 '超时多少秒
        Do
        DoEvents
        wait 10
        waitTimeOut = waitTimeOut + 1
        Loop Until (aHttpRequest.ReadyState = 4 Or waitTimeOut >= 100 * secondNumber)
        If aHttpRequest.ReadyState = 4 Then
            sResponse = aHttpRequest.ResponseText            
        Else
            sResponse = ""
        End If
    Else
        If sMethod = "GET" Then
            sBody = Replace(sBody, "?", "")
            sURL = sURL & "?" & sBody
        End If
        '创建WinHttp.WinHttpRequest
        Set aHttpRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
        '' 同步接收数据
        aHttpRequest.Open sMethod, sURL, False
        '' 非常重要(忽略错误)
        aHttpRequest.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = &H3300
        '' 其它请求头设置]
        If InStr(1, sBody, "?") > 0 Then
            sBody = Replace(sBody, "?", "") '有些接口不支持带?
            aHttpRequest.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    '        aHttpRequest.SetRequestHeader "Cookie", "a:x,"
            aHttpRequest.SetRequestHeader "Content-Length", Len(sBody)
            aHttpRequest.SetTimeouts 100000, 100000, 100000, 100000        '设置超时时间 100秒
        Else
            aHttpRequest.SetRequestHeader "Authorization", "Basic a2luZ2RlZTpraW5nZGVlJDIwMTQjZQ=="
            aHttpRequest.SetRequestHeader "Content-Type", "application/json;charset=UTF-8"            
            aHttpRequest.SetTimeouts 100000, 100000, 100000, 100000        '设置超时时间 100秒
        End If
        aHttpRequest.Send sBody
        '' 得到返回文本(或者是其它)
        sResponse = aHttpRequest.ResponseText
    End If
   GetResponse = sResponse    
    Set aHttpRequest = Nothing
End Function

你可能感兴趣的:(VB6.0)