2014-03-03 39 views
3

我試圖寫一個VBA宏將通過我的credentails到一個地址,並獲取了一些內容(REST API的JIRA),但我有一些困難,從Java轉換我的代碼到VBA。目前,這是我的Java代碼:如何通過身份驗證憑據在VBA

 String username = "myUser"; 
     String password = "myPassword"; 

     String authString = username + ":" + password; 
     byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); 
     String authStringEnc = new String(authEncBytes); 
     System.out.println("Base64 encoded auth string: " + authStringEnc); 

     URL url = new URL(address); 
     URLConnection urlConnection = url.openConnection(); 
     urlConnection.setRequestProperty("Authorization", "Basic " 
       + authStringEnc); 
     InputStream is = urlConnection.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(is); 

我試圖將其轉換爲VBA,我不完全知道如何處理它,或者,如果有一些庫,將有助於這一點。

回答

2

對於基本身份驗證您可以簡單:

Dim response As String 

With CreateObject("Microsoft.XMLHTTP") 
    .Open "GET", address, false, username, password 
    .Send 
    response = .responseText 
End With 

Msgbox response 
+0

我和HTTPS進行了測試,它完美的作品。最簡單的解決方案。 – Unicco

2

使用 「授權」 請求頭。 「授權」請求標題需要用戶名和密碼的加密字符串。

.setRequestHeader "Authorization", "Basic " & EncodeBase64 

所以這裏JiraService作爲一個XMLHTTP對象,這樣的事情將要驗證,其中EncodeBase64是返回加密的字符串的函數。

Public Function isAuthorized() As Boolean 
With JiraService 
    .Open "POST", sURL & "/rest/api/2/issue/", False 
    .setRequestHeader "Content-Type", "application/json" 
    .setRequestHeader "Accept", "application/json" 
    .setRequestHeader "Authorization", "Basic " & EncodeBase64 
    .send "" 
    If .Status <> 401 Then 
     isAuthorized = True 
    Else 
     isAuthorized = False 
    End If 
End With 

Set JiraService = Nothing 
End Function 

您可以檢查出complete VBA example here

相關問題