-2

how can I convert a String into a Url. some thing like following example. i want to encode https://abc.com/msds/AFALON MSDS.pdf into https://abc.com/msds/AFALON%20MSDS.pdf.

Samantha Withanage
  • 3,811
  • 10
  • 30
  • 59

2 Answers2

1

According to javadocs:

When encoding a String, the following rules apply:

  1. The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.
  2. The special characters ".", "-", "*", and "_" remain the same.
  3. The space character " " is converted into a plus sign "+".
  4. All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

try like this

System.out.println(URLEncoder.encode(
         "https://abc.com/msds/AFALON MSDS.pdf", "UTF-8").replace("+", "%20"));
SparkOn
  • 8,806
  • 4
  • 29
  • 34
  • 'replace("+", "%20"))' part makes the change. it replaces the '+' marks into '%20' and creates a working url. although 'encode' creates a url consists of "+" it does not working. anyway thanks a lot. – Samantha Withanage Aug 28 '14 at 10:15
0

Use http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html and call the encode() method

Neeraj Krishna
  • 1,527
  • 2
  • 16
  • 22