Languages
[Edit]
EN

Java - encodeURIComponent equivalent in JavaScript

10 points
Created by:
Root-ssh
115700

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

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

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

// import java.net.URLEncoder;

String text = "Hi! How are you? Dangerous characters: ?#&";

String encodedText = URLEncoder.encode(text, StandardCharsets.UTF_8.name());

encodedText = encodedText.replaceAll("\\+", "%20");
encodedText = encodedText.replaceAll("%21", "!");
encodedText = encodedText.replaceAll("%27", "'");
encodedText = encodedText.replaceAll("%28", "(");
encodedText = encodedText.replaceAll("%29", ")");
encodedText = encodedText.replaceAll("%7E", "~");

System.out.println(encodedText);  // Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26

Output:

Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26

 

Note: check decodeURIComponent function Java equivalent here.

Reusable code example

URIEncoder.java file:

package com.dirask.examples;

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

public class URIEncoder {

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

    private static final String[][] CHARACTERS = {
        { "\\+", "%20" },
        { "%21", "!"   },
        { "%27", "'"   },
        { "%28", "("   },
        { "%29", ")"   },
        { "%7E", "~"   }
    };

    public static String encodeURIComponent(String text) {
        String result;
        try {
            result = URLEncoder.encode(text, CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        for(String[] entry : CHARACTERS) {
            result = result.replaceAll(entry[0], entry[1]);
        }
        return result;
    }
}

Program.java file:

package com.dirask.examples;

import java.io.UnsupportedEncodingException;

public class Program {

    public static void main(String[] args) {

        String text = "Hi! How are you? Dangerous characters: ?#&";
        String encodedText = URIEncoder.encodeURIComponent(text);

        System.out.println(encodedText);
    }
}

Output:

Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26

See also

  1. Java - decodeURIComponent equivalent in JavaScript 
  2. JavaScript - encode / escape 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