Sunday, 11 October 2015

JAVA URLEncoder : form encoding


URLEncoder class is used for HTML form encoding. This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format. URLEnocder class converts any non alpha-numeric characters (except ".", "-", "*", and "_") to %sequences.

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

public class Main {
  public static void main(String args[]) throws URISyntaxException, UnsupportedEncodingException {
    String data = "Simple text data!@#$";
    
    String encodeData = URLEncoder.encode(data, "UTF-8");
    System.out.println(encodeData);
  }
}

Output
Simple+text+data%21%40%23%24

Why should we encode URLs?
Consider for example, in a query string, the ampersand (&) is used as a separator between key and value pairs (name=krishna&age=26). If any of the parameter value has an ampersand in it, it would look like the separator between the end of a value and the beginning of the next key. So for special characters like this, we use URL encoding so that we can be sure that the data is unambiguously encoded.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment