在 Scala 中调用 API 时传递凭据

我正在尝试使用 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.mkString

inputStream.close

httpClient.getConnectionManager().shutdown()

return content

看起来BasicScheme在“org.apache.http.impl.auth”中被弃用。关于如何前进的任何指示...提前致谢。


白衣染霜花
浏览 77回答 1
1回答

MYYA

鉴于您尝试使用基本身份验证,这应该足够了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())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java