为了账号安全,请及时绑定邮箱和手机立即绑定

在 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 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信