Here is one example of how the Kotlin package does so:
import org.ton.crypto.base64
import org.ton.crypto.base64url
fun convert(address: String): String {
val raw = try {
base64url(address)
} catch (E: Exception) {
base64(address)
}
return raw;
}