Pass credentials while calling an API in Scala

Anil :

I'm trying to call a REST endpoint using HttpGet and pass user credentials.

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

Looks like BasicScheme is deprecated in "org.apache.http.impl.auth". Any pointers on how to move forward... Thanks in Advance.

LppEdd :

Given you're trying to use basic authentication, this should be sufficient

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)

If instead you prefer going with a simple HTTP header, you can use

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())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151124&siteId=1