Tuesday 27 June 2017

How to encode url in java?

java.net.URLEncoder class provides 'encode' method to encode url.

public static String encode(String s, String encodingScheme)
Encode the url using given encoding scheme.

Every standard Java implementation must support below encoding schemes.

1.   US-ASCII
2.   ISO-8859-1
3.   UTF-8
4.   UTF-16BE
5.   UTF-16LE
6.   UTF-16

'java.nio.charset.Charset' class provides 'isSupported' method to check whether given character encoding is supported by your Java implementation or not.

Below program encodes a url and print the encoded url to the console.
package com.sample;

import java.io.UnsupportedEncodingException;

public class URLEncoder {

 public static void main(String args[]) throws UnsupportedEncodingException {

  String encodedURL = java.net.URLEncoder.encode("https://self-learning-java-tutorial.blogspot.com/2014/09/servlets.html", "UTF-8");
  System.out.println("encodedURL : " + encodedURL);
  
 }
}


No comments:

Post a Comment