How to Encode URL String Or Form Parameter in Java


In this example, we will see how to encode a URL string or form parameter in Java.

Source Code

package com.beginner.examples;

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

public class EncodeURLOrFormParameter {

	public static void main(String[] args) {
		try {
			String url = "http://www.google.com";
			String encodedURL = URLEncoder.encode(url, "UTF-8");
			System.out.println("Encoded URL is :" + encodedURL);
			String decodedURL = URLDecoder.decode(url, "UTF-8");
			System.out.println("Dncoded URL is :" + decodedURL);
		}catch(UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

}

Output:

Encoded URL is :http%3A%2F%2Fwww.google.com
Dncoded URL is :http://www.google.com

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments