How to encode and decode the URL
Example:
Input: https://beingcodeexpert.blogspot.com/?q=Java%20Is%20programming%20language Output: https://beingcodeexpert.blogspot.com/?q=Java Is programming language
Approach: Encode
Java
import java.io.UnsupportedEncodingException;import java.net.MalformedURLException;import java.net.URISyntaxException;import java.net.URLDecoder;import java.net.URLEncoder;public class EncodeURL {public static void main(String[] args) throws URISyntaxException, MalformedURLException {String url2 = "https://beingcodeexpert.blogspot.com/?q=Java Is programming language";String encodeURL = encode(url2);System.out.println("Encoded URL2: " + encodeURL);}public static String encode(String url) {try {String encodeURL = URLEncoder.encode(url, "UTF-8");return encodeURL;} catch (UnsupportedEncodingException e) {return "Issue while encoding" + e.getMessage();}}}
Approach: Decode
Java
import java.io.UnsupportedEncodingException;import java.net.MalformedURLException;import java.net.URISyntaxException;import java.net.URLDecoder;public class EncodeURL {public static void main(String[] args) throws URISyntaxException, MalformedURLException {String url = "https://beingcodeexpert.blogspot.com/?q=Java%20Is%20programming%20language";String decodeURL = decode(url);System.out.println("Decoded URL: " + decodeURL);}public static String decode(String url) {try {String prevURL = "";String decodeURL = url;while (!prevURL.equals(decodeURL)) {prevURL = decodeURL;decodeURL = URLDecoder.decode(decodeURL, "UTF-8");}return decodeURL;} catch (UnsupportedEncodingException e) {return "Issue while decoding" + e.getMessage();}}}
No comments:
Post a Comment