java - 在 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”中已被弃用。关于如何前进的任何指示......在此先感谢。
解决方案
鉴于您正在尝试使用基本身份验证,这应该足够了
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())
推荐阅读
- boundary - 尝试 ssh 连接时,Hashicorp 边界抛出失败到 WebSocket 拨号
- fpga - Vitis:将 16 字节变量存储到 4 个 32 位寄存器中
- python - python lxml:无法通过标签+命名空间找到节点
- python - 熊猫模式中的困惑()
- postgresql - 选择没有空格的行postgresql
- php - PHP:Laravel 查询优化
- javascript - 使用 JavaScript 获取数据和标记 html 表的最有效方法
- python - AssertionError:视图函数映射正在覆盖现有端点函数:newRoom
- php - php打印中的三元运算符?
- c# - 自动引发 WM_NCHITTEST 消息以形成 WndProc