亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Scala 中調用 API 時傳遞憑據

在 Scala 中調用 API 時傳遞憑據

白衣染霜花 2022-09-07 21:18:44
我正在嘗試使用 HttpGet 調用 REST 終結點并傳遞用戶憑據。var content = ""val httpClient : CloseableHttpClient = HttpClients.createDefault();val httpResponse = new HttpGet(url)httpResponse.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(“uname”,”pwd”),”UTF-8", false))val response = httpClient.execute(httpResponse)val entity = httpResponse.getEntity()val inputStream = entity.getContent()content = fromInputStream(inputStream).getLines.mkStringinputStream.closehttpClient.getConnectionManager().shutdown()return content看起來BasicScheme在“org.apache.http.impl.auth”中被棄用。關于如何前進的任何指示...提前致謝。
查看完整描述

1 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

鑒于您嘗試使用基本身份驗證,這應該足夠了


val credentialsProvider = new BasicCredentialsProvider()

credentialsProvider.setCredentials(

    AuthScope.ANY, 

    new UsernamePasswordCredentials("username", "password")

)


val httpClient = 

    HttpClientBuilder.create()     

                     .setDefaultCredentialsProvider(credentialsProvider)

                     .build()


val httpResponse = new HttpGet(url)

httpClient.execute(httpResponse)

相反,如果您更喜歡使用簡單的HTTP標頭,則可以使用


def buildEncodedCredentials(): String = {

    val credentialsString = username + ":" + password

    val charset = StandardCharsets.ISO_8859_1

    val encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(charset))

    return new String(encodedBytes, charset)

}

 httpResponse.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + buildEncodedCredentials())


查看完整回答
反對 回復 2022-09-07
  • 1 回答
  • 0 關注
  • 88 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號