Languages
[Edit]
EN

Java - decodeURIComponent equivalent in JavaScript

6 points
Created by:
Kadeem-Craig
456

In this article, we would like to show how to get JavaScript decodeURIComponent function equivalent in Java.

Using Java, sometimes it is necessary to decode some data to send inside URL. JavaScript provides well known decodeURIComponent function.

To get the same effect in Java it is necessary to do the following code:

// import java.net.URLDecoder;

String text = "Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26";
String decodedText = URLDecoder.decode(text, StandardCharsets.UTF_8.name());

System.out.println(decodedText);  // Hi! How are you? Dangerous characters: ?#&

Output:

Hi! How are you? Dangerous characters: ?#&

 

Note: check encodeURIComponent function Java equivalent here.

1. Reusable code example

URIDecoder.java file:

package com.dirask.examples;

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

public class URIDecoder {

    private static final String CHARSET = StandardCharsets.UTF_8.name();

    public static String decodeURIComponent(String text) {
        try {
            return URLDecoder.decode(text, CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

Program.java file:

package com.dirask.examples;

import java.io.UnsupportedEncodingException;

public class Program {

    public static void main(String[] args) {

        String text = "Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26";
        String decodedText = URIDecoder.decodeURIComponent(text);

        System.out.println(decodedText);
    }
}

Output:

Hi! How are you? Dangerous characters: ?#&

See also

  1. Java - encodeURIComponent equivalent in JavaScript

  2. JavaScript - decode url characters
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join