URL authentication

I can’t connect with a URL. Server return HTTP response code: 401 for URL:

def getPdf(factura: String): String = {
val url = “http://ip adress/dte_pdf/”+ factura
val username = “valid user”
val password = valid password"
val connection = new URL(url).openConnection
val userpass = username + “:” + password;
val basicAuth = "Basic " +
javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
connection.setRequestProperty(“Authorization”, basicAuth);
scala.io.Source.fromURL(url).mkString
}

What is wrong?

TIA

AUGUSTO

HTTP code 401 means your authorization failed. This is because you don’t pass the username and password to the part of the code, where you do the request:

// creates a URLConnection object
val connection = new URL(url).openConnection
...
// adds the authentication info to that connection. Does NOT change the url object
connection.setRequestProperty(“Authorization”, basicAuth);
// uses the url instead of the connection, i.e. no credentials
scala.io.Source.fromURL(url).mkString

Scala’s Source can read from an InputStream, so changing the last line to

scala.io.Source.fromInputStream(connection.getInputStream).mkString

should help.

1 Like

Yes!, thank you… AUGUSTO