suraj
suraj

Reputation: 1898

String Encoding in java

I have a String String a="123+>jo I want to en code the String so that I can redirect it to an url. I initially tried it with urlencoder but in urldecoder +(plus) is removed while decoding.So i lost my data.

What is the right way to encode so that I get the same string while decoding also?

Upvotes: 1

Views: 351

Answers (1)

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

URLEncoder works perfectly. The plus sign is succesfully encoded into %2B.

Encoding: Works

Here is the IDEONE project: http://ideone.com/zMDur

import java.net.URLEncoder;

// ...

    public static void main (String[] args) throws java.lang.Exception
    {
            String str = "123+>jo";
            String str2 = "http://1.com/23+>jo";
            System.out.println(URLEncoder.encode(str));
            System.out.println(URLEncoder.encode(str2));
    }

prints:

123%2B%3Ejo
http%3A%2F%2F1.com%2F23%2B%3Ejo

Encoding + Decoding: Works

The IDEONE project with decoding as well: http://ideone.com/Ypfv4

import java.net.URLEncoder;
import java.net.URLDecoder;

// ...

    public static void main (String[] args) throws java.lang.Exception
    {
            String str = "123+>jo";
            String str2 = "http://1.com/23+>jo";
            System.out.println(URLDecoder.decode(URLEncoder.encode(str)));
            System.out.println(URLDecoder.decode(URLEncoder.encode(str2)));
    }

Prints:

123+>jo
http://1.com/23+>jo

So everything works using the java.net.URLEncoder and java.net.URLDecoder.

Upvotes: 2

Related Questions