5

------Update Was able to fix it by using the UsernamePasswordCredentials class The code looks like below val client = new DefaultHttpClient client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("user","password"));

i am trying to make a HttpPost call to a Restful API, its expecting a username/password, how to pass those parameters? I tried 2 ways

post.addHeader("Username","user")
post.addHeader("Password","clear pwd")
and 
post.addHeader("Authorization","Basic base64encoded username:password")

nothing works, I get response text as

Response Text = HTTP/1.1 401 Unauthorized [WWW-Authenticate: Digest realm="API Realm", domain="/default-api", nonce="pOxqalJKm5L5QXiphgFNmrtaJsh+gU", algorithm=MD5, qop="auth", stale=true, Content-Type: text/html; charset=ISO-8859-1, Cache-Control: must-revalidate,no-cache,no-store, Content-Length: 311] org.apache.http.conn.BasicManagedEntity@5afa04c

Below is my code

val url = "http://restapi_url";
val post = new HttpPost(url)

//post.addHeader("Authorization","Basic QWBX3VzZXI6Q0NBQGRidHMxMjM=")
post.addHeader("Username","user_user")
post.addHeader("Password","clear pwd")
post.addHeader("APPLICATION_NAME","DO")
val fileContents = Source.fromFile("input.xml").getLines.mkString
post.setHeader("Content-type", "application/xml")
post.setEntity(new StringEntity(fileContents))

val response = (new DefaultHttpClient).execute(post)

println("Response Text = "+response.toString())

// print the response headers
println("--- HEADERS ---")
response.getAllHeaders.foreach(arg => println(arg))
vitruvian
  • 63
  • 1
  • 5
  • Duplication: http://stackoverflow.com/questions/29995749/with-what-can-i-replace-http-deprecated-methods – Marten Jan 27 '17 at 15:58
  • Possible duplicate of [With what can I replace http deprecated methods?](http://stackoverflow.com/questions/29995749/with-what-can-i-replace-http-deprecated-methods) – Jed Fox Jan 27 '17 at 17:29

3 Answers3

1

Here the authorization header should be calculated like this:

httpPost.addHeader("Authorization", "Basic " + Base64.getEncoder.encodeToString("[your-username]:[your-password]".getBytes))

Instead of getUrlEncoder(), it should be getEncoder().

ABHITRNG
  • 91
  • 5
0

you can write like this, it works in my program

import java.util.Base64

httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder.encodeToString("[your-username]:[your-password]".getBytes))
Cheng
  • 11
  • 1
0

DefaultHttpClient is deprecated. You should use BasicCredentialsProvider instead. Example code below:

val username = "your_username"
val password = "your_password"

    val credentialsProvider = new BasicCredentialsProvider()
    credentialsProvider.setCredentials(
      AuthScope.ANY,
      new UsernamePasswordCredentials(username, password)
    )

val httpClient =  HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build()
Ceus
  • 11
  • 7