-2

int a=50;

How do I encode this using URLEncoder?

For strings we do

String value=URLEncoder.encoder("SomeStringValye",this.encoding);
node_modules
  • 4,790
  • 6
  • 21
  • 37
suman joshi
  • 33
  • 2
  • 8
  • 3
    why do you need to encode an int? – Scary Wombat Jun 06 '16 at 07:12
  • 1
    Wombat is right ... you know, you can turn an int into a String pretty easily ... – GhostCat Jun 06 '16 at 07:12
  • so you are saying i should convert the int value to string and then encode it ? or encoding an integer value is not advisable ? – suman joshi Jun 06 '16 at 07:38
  • The number `50` is the string `"50"` and since digits, `-`, and `.` are not special characters in URLs, you don't need to encode numbers. Encoding will do nothing, so it doesn't hurt. Remember, a URL is a string, so any value you want must be formatted as a string first, then encoded to escape special characters. – Andreas Jun 06 '16 at 07:46

1 Answers1

1

Integer numbers in the URL are not an issue. You need not URL encode it. So in your case, simply construct a url by concatenating as follows

String s = "www.xyz.com/?id=" +1; 

If you have some special characters in your url parameter like space, ;, then you have to url encode the parameter value

URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString() )

If you still want to pass the integer to the URL encoder method, simply make your integer as a string e.g., 10+""

David Chelliah
  • 1,319
  • 1
  • 13
  • 24
  • Why use string concatenation of two string literals? --- Remove that `'`. --- You *may* also encode the string-formatted number. Did you mean "must"? – Andreas Jun 06 '16 at 07:49