How to encode the URL
Example:
Input: Java Is programming language
Output: https://beingcodeexpert.blogspot.com/?q=Java%20Is%20programming%20language
Approach
Java
import java.net.MalformedURLException;import java.net.URISyntaxException;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;public class EncodeURL {public static void main(String[] args) throws URISyntaxException, MalformedURLException {String q = "Java Is programming language";String urlE = "https://beingcodeexpert.blogspot.com/?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);System.out.println(urlE);}}
Java
import java.net.IDN;import java.net.MalformedURLException;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;public class EncodeURL {public static void main(String[] args) throws URISyntaxException, MalformedURLException {String q = "Java Is programming language";URL url = new URL("https://beingcodeexpert.blogspot.com/?q=" + q);URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(),url.getPath(), url.getQuery(), url.getRef());String correctEncodedURL = uri.toASCIIString();System.out.println(correctEncodedURL);}}
Approach
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();}}}
No comments:
Post a Comment