卷曲到VBA转换

时间:2019-03-22 17:08:09

标签: excel vba curl

此api代码的等效VBA是什么(用于Name.com域检查API):

curl -u'username:token''https://api.dev.name.com/v4/domains:checkAvailability'-X POST --data'{“ domainNames”:[“ example.org”]}'

尝试:

for_each

它说:“消息:”,“未经身份验证”

注意: 对于GoDaddy域可用性API,该转换有效:

卷曲-X GET -H“授权:sso-key [API_KEY]:[API_SECRET]”“ https://api.godaddy.com/v1/domains/available?domain=

VBA:

Set request = CreateObject("WinHttp.WinHttpRequest.5.1") '
url = "https://api.dev.name.com/v4/domains:checkAvailability"
request.Open "POST", url, False
request.setRequestHeader "username:token", "???:???"
or 
request.SetCredentials "username", "token", 0
request.setRequestHeader "domainNames", Range("C1").Value & ".com"
request.Send
MsgBox request.ResponseText

(用户名和令牌/密钥(???)已隐藏)

此外,对于“ whois.internic.net”查询,(正在运行的)VBA代码示例

3 个答案:

答案 0 :(得分:0)

您可以尝试XMLHTTP并查看它是否对打开方法有什么影响,包括用户名和令牌?

def add_assessment(self, record, map_data):
    """Create contact log"""
    qna_frame = self.driver.find_element_by_css_selector("iframe[id^='iccc']")
    self.driver.switch_to.frame(qna_frame)

    pages = self.driver.find_element_by_css_selector("ul[class='nav nav-pills nav-stacked qna-tabs']")
    pages = pages.find_elements_by_css_selector("a")

    for page in pages:
        page.click()

        questions = self.driver.find_elements_by_css_selector("fieldset")
        questions = [question for question in questions if question.text not in  ("", " ", None)]

        for question in questions[1:]:
            self.q_text = question.find_element_by_css_selector("span[class='question-text ng-binding']").text
            questionType = map_data.loc[map_data['question_text'] == self.q_text, 'question_type'].item()

            answer = map_data.loc[map_data['question_text'] == self.q_text, 'map'].item()
            answer = getattr(record, answer)

            if answer not in ("", " ", "NaT", "NaN", None):
            # while answer != "" and answer != " " and answer != "NaT":

                if questionType == 'checks':
                    self.choose_checks(question, answer)
                else:
                    try:
                        if questionType == 'text':
                            self.driver.implicitly_wait(0)

                            (question.find_element_by_css_selector("textarea").send_keys(str(answer))
                            if 
                                question.find_elements_by_css_selector("textarea")
                            else 
                                question.find_element_by_css_selector("input").send_keys(answer))

                            self.driver.implicitly_wait(15)

                        elif questionType == 'date':
                            try:
                                answer = answer.strftime('%m/%d/%Y')
                                question.find_element_by_css_selector("input").send_keys(answer)
                                page.click()

                            except Exception as e:
                                raise Errors.RequiredDataError('Issues with Assessment Date -- {}'.format(e))
                        elif questionType == 'radio':
                            question.find_element_by_css_selector("input[value='{}']".format(answer)).click()
                    except:
                        continue                              
                    else:
                        # driver.find_element_by_css_selector("#publishButton").click()
                        pass   

答案 1 :(得分:0)

为什么不直接使用curl(通过Windows Shell):

对于以下代码,您设置了对Windows Script Host Object Model的引用以进行早期绑定。

当然,我无法对其进行测试,因为它返回“权限被拒绝”,我认为这是由于无效的用户名:令牌造成的。

请注意引号字符串中包含的引号的""转义引号。

Option Explicit
Sub curl()
    Const strCurl As String = """username:token"" ""https://api.dev.name.com/v4/domains:checkAvailability"" -X POST --data ""{""domainNames"":[""example.org""]}"""
    Dim WSH As WshShell, lErrCode As Long
    Dim FSO As FileSystemObject, TS As TextStream
    Dim sTemp As String
    Dim sBasePath As String
    Dim I As Long
    Dim strJson As String

    sTemp = Environ("Temp") & "\FileList.txt"



Set WSH = New WshShell
lErrCode = WSH.Run("CMD /c curl -u" & strCurl & " > " & sTemp, xlHidden, True)

'lErrCode = WSH.Run("CMD /c tree """ & sBasePath & """ /F /A > " & sTemp, xlHidden, True)

If Not lErrCode = 0 Then
    MsgBox "Problem " & "Error Code " & lErrCode
    Exit Sub
End If


Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile(sTemp, ForReading, False, TristateFalse)
strJson = TS.ReadAll
TS.Close

FSO.DeleteFile sTemp
Set FSO = Nothing
Set WSH = Nothing

Stop 'see what's in the string.
     'if it worked, then you can parse the results

End Sub

答案 2 :(得分:0)

您需要对身份验证详细信息进行base64编码,并传入标头并传递正文中的域列表。我已经使用jsonconverter.bas来解析json响应。添加bas之后,您需要添加如下所示的参考。另外,添加对Microsoft xml的引用

Public Sub GetResults()
    Dim data As String, json As Object '<  VBE > Tools > References > Microsoft Scripting Runtime
    data = "{""domainNames"":[""google.com""]}"
    With CreateObject("WinHttp.WinHttpRequest.5.1")
        .Open "POST", "https://api.dev.name.com/v4/domains:checkAvailability", False
        .setRequestHeader "User-Agent", "Mozilla/5.0"
        .setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
        .setRequestHeader "Authorization", "Basic " + _
            EncodeBase64("username" + ":" + "Token")
        .send data
        Set json = JsonConverter.ParseJson(.responseText)
        Dim result As Object
        For Each result In json("results")
            Debug.Print result("domainName")
        Next
    End With
End Sub

Function EncodeBase64(text As String) As String


  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As MSXML2.DOMDocument60
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument60
  Set objNode = objXML.createElement("b64")

  objNode.DataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = Application.Clean(objNode.text)

  Set objNode = Nothing
  Set objXML = Nothing
End Function

base64函数取自here / here

如果您了解python,则可以执行以下操作:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}

data = '{"domainNames":["google.com"]}'

result = requests.post('https://api.dev.name.com/v4/domains:checkAvailability', data=data, headers = headers, auth=('username','token')).json()
print(result['results'])