Wednesday 6 August 2014

How do I encode URL parameters

When using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands.

However, what happens if the parameter value in the URL string has a space or some other special character? Submitting an HTML form will result in special characters being automatically converted to special codes for us. However, sometimes it is necessary to encode these characters without the aid of an HTML form. Java  has a class called URLEncoder that can encode these characters so that they are properly handled. The encode method takes two parameters, the string to be encoded and the encoding scheme. Unless you're smoking crack, you probably want the encoding scheme to be "UTF-8".




Below is the Sample Code:



import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class UrlEncoderTest {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String param1Before = "hello there";
        String param1After = URLEncoder.encode(param1Before, "UTF-8");
        System.out.println("param1 before:" + param1Before);
        System.out.println("param1 after:" + param1After);

        String param2Before = "good-bye, friend";
        String param2After = URLEncoder.encode(param2Before, "UTF-8");
        System.out.println("param2 before:" + param2Before);
        System.out.println("param2 after:" + param2After);

    }

}


OutPut:

param1 before:hello there
param1 after:hello+there
param2 before:good-bye, friend
param2 after:good-bye%2C+friend




No comments:

Post a Comment