How to Encode and Decode URL String in Java


Here we will learn how to encode and decode URL string in Java. The URLEncoder class is used for encoding, and the URLDecoder class is used for decoding.

Source Code

package com.beginner.examples;

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

public class URLDecoderTest {

	public static void main(String[] args) {

		try {
			//Encode the given string
			String encoderStr = URLEncoder.encode("I want something just like this", "utf-8");
			//decoding
			String decoderStr = URLDecoder.decode(encoderStr, "utf-8");

			System.out.println("EncoderStr: " + encoderStr + "nDecoderStr: " + decoderStr);

		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}

	}

}

Output:

EncoderStr: I+want+something+just+like+this
DecoderStr: I want something just like this

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments