Chain the http if the condition is met

I would like to do something like this:

  val httpProtocol: HttpProtocolBuilder = http
    .baseUrl(system_env)
    .acceptHeader("application/json")
    .acceptEncodingHeader("gzip, deflate, br")

    if(proxyEnabled) {
      httpProtocol.proxy(Proxy("proxy_server", port)
        .httpsPort(port)
        .credentials(proxyUsername, proxyPassword))
    }

But it doesn’t work for some reason with that if statement there.
When I have it like this:

  val httpProtocol: HttpProtocolBuilder = http
    .baseUrl(system_env)
    .acceptHeader("application/json")
    .acceptEncodingHeader("gzip, deflate, br")
    .proxy(Proxy("proxy_server", port)
        .httpsPort(port)
        .credentials(proxyUsername, proxyPassword))

then my proxy is taken into account.
How to do this properly?

Never mind, I got it.
It should be:

  var httpProtocol: HttpProtocolBuilder = http
    .baseUrl(system_env)
    .acceptHeader("application/json")
    .acceptEncodingHeader("gzip, deflate, br")

    if(proxyEnabled) {
      httpProtocol = httpProtocol.proxy(Proxy("proxy_server", port)
        .httpsPort(port)
        .credentials(proxyUsername, proxyPassword))
    }

Sorry, maybe it will help someone :slight_smile:

Hi @mrukavina,

Indeed, as preferred in scala programming, we favor immutable values.

Good you found that by yourself!

I suggest that you go one step beyond:

val httpProtocol: HttpProtocolBuilder = {
  val baseProtocol = http
    .baseUrl(system_env)
    .acceptHeader("application/json")
    .acceptEncodingHeader("gzip, deflate, br")

  if (proxyEnabled) {
    baseProtocol.proxy(Proxy("proxy_server", port)
        .httpsPort(port)
        .credentials(proxyUsername, proxyPassword))
  } else {
    baseProtocol
  }
}

Cheers!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.