您好,我需要使用 Groovy 的基本身份驗證連接到 url,我更愿意在不使用任何庫的情況下實作這一點,因為在我們的專案中,我們掃描了漏洞,有時我們在包含新庫時會遇到問題。我正在關注下一個例子:
def connection = new URL( "https://jsonplaceholder.typicode.com/posts")
.openConnection() as HttpURLConnection
// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )
// get the response code - automatically sends the request
println connection.responseCode ": " connection.inputStream.text
它有效,但在我的情況下,我需要使用基本身份驗證(用戶名和密碼)進行連接。我還沒有看到相關的例子。
有任何想法嗎?
謝謝!
uj5u.com熱心網友回復:
https://en.wikipedia.org/wiki/Basic_access_authentication
在基本的 HTTP 身份驗證中,請求包含一個頭欄位,格式為
Authorization: Basic <credentials>
其中<credentials>ID 和密碼的 Base64 編碼由單個冒號連接:。
在 groovy 中,它可能如下所示:
def user = ...
def pass = ...
def auth = "${user}:${pass}".bytes.encodeBase64()
connection.setRequestProperty("Authorization", "Basic ${auth}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398120.html
