首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Scala中调用API时传递凭据

在Scala中调用API时传递凭据
EN

Stack Overflow用户
提问于 2019-03-27 18:43:32
回答 1查看 1.1K关注 0票数 2

我试图使用HttpGet调用REST端点并传递用户凭据。

代码语言:javascript
运行
复制
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“中不受欢迎。任何关于如何前进的建议..。提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-27 19:10:34

如果您正在尝试使用基本身份验证,这应该就足够了

代码语言:javascript
运行
复制
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头,则可以使用

代码语言:javascript
运行
复制
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)
}
代码语言:javascript
运行
复制
 httpResponse.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + buildEncodedCredentials())
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55384442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档