Ishq Mehta
Ishq Mehta

Reputation: 387

Error in building a URL string in java

I am having a hard time in building a URL string which I want to use for HttpURLConnection.

Here is the string that I want to pass

http://api.fixer.io/latest?base=USD&symbols=USD,GBP

The above string shall have all the parameter as dynamic, two Strings that I am using are part1 and other default_actv2

I tried building string in following way

http://api.fixer.io/latest?base="+part1+"&symbols="+part1+","+default_actv2 

and passing it into jsonTask in following way

new JSONTask().execute("http://api.fixer.io/latest?base="+part1+"&symbols="+part1+","+default_actv2);

When I print the value my code takes it as

http://api.fixer.io/latest?base=AED &symbols=AED ,INR

Notice the extra spaces after AED, as a result of such a string. I am getting error from the server side.

Could anybody help in explaining me the correct way of building a string with some code. I know there are tons of threads that answers this question, but somehow I am not able to get this thing working.

Thanks In advance

Upvotes: 1

Views: 140

Answers (2)

ouzman
ouzman

Reputation: 71

You can use Apache URIBuilder.

URI uri = new URIBuilder()
        .setScheme("http")
        .setHost("api.fixer.io")
        .setPath("/latest")
        .addParameter("base", part1)
        .addParameter("symbol", part1 + "," + default_actv2)
        .build();
uri.toString();

Upvotes: 2

Que
Que

Reputation: 136

You can use .trim() on your part1 string in order to deal with the extra space.

Upvotes: 3

Related Questions