How to build URL in Groovy

IAmYourFaja picture IAmYourFaja · Jun 13, 2014 · Viewed 10.4k times · Source

I think, I want to use URIBuilder here but not entirely sure...

I have the following code:

String serverURL = getServerURL(); // ex: "http://somesrv.example.com"
String appURL = getAppURL(); // ex: "http://myapp.example.com"

I now need to add the two together, so that it produces the following:

http://somesrv.example.com/fizz?widget=http://myapp.example.com

But I don't just want to use string bashing (def url = serverURL + "/fizz?widget=" + appURL). Plus I'd like URL encoding, etc. Again, I think URLBuilder is the way to go here, but not sure.

I've seen an example uses JAX-RS' UriBuilder:

String url = UriBuilder.fromUri(serverURL).path("fizz").queryParam("widget", appURL).build();

Now I just need to figure out how to do this in Groovy?

Answer

SiKing picture SiKing · Jun 13, 2014

URIBuilder is the way to go.

def serverURL = "http://somesrv.example.com"
def appURL = "http://myapp.example.com"

def concat = new URIBuilder(serverURL)
concat.setPath("/fizz")
concat.addQueryParam("widget", appURL)

println concat

Outputs:

http://somesrv.example.com/fizz?widget=http%3A%2F%2Fmyapp.example.com