Languages
[Edit]
EN

Java - encodeURIComponent equivalent in JavaScript

10 points
Created by:
Root-ssh
133690

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

Optimal solution

Multiple replaceAll() calls in the above examples require multiple iterations through the encoded string.

In this section, you will find the optimal solution.

package com.dirask.examples;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class URIEncoder {

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

    public static String encodeURIComponent(String text) {
        if (text.isEmpty()) {
            return "";
        }
        String code;
        try {
            code = URLEncoder.encode(text, CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        int textLength = text.length();
        int codeLength = code.length();
        StringBuilder builder = new StringBuilder((textLength + codeLength + 1) / 2);
        for (int i = 0; i < codeLength; ++i) {
            char entry = code.charAt(i);
            switch (entry) {
                case '+':
                    builder.append("%20");
                    break;
                case '%':
                    if (i > codeLength - 2) {
                        break;
                    }
                    char a = code.charAt(i += 1);
                    char b = code.charAt(i += 1);
                    switch (a) {
                        case '2':
                            switch (b) {
                                case '1':
                                    builder.append("!");
                                    break;
                                case '7':
                                    builder.append("'");
                                    break;
                                case '8':
                                    builder.append("(");
                                    break;
                                case '9':
                                    builder.append(")");
                                    break;
                                default:
                                    builder.append("%");
                                    builder.append(a);
                                    builder.append(b);
                                    break;
                            }
                            break;
                        case '7':
                            if (b == 'e' || b == 'E') {
                                builder.append("~");
                            } else {
                                builder.append("%");
                                builder.append(a);
                                builder.append(b);
                            }
                            break;
                        default:
                            builder.append("%");
                            builder.append(a);
                            builder.append(b);
                            break;
                    }
                    break;
                default:
                    builder.append(entry);
                    break;
            }
        }
        return builder.toString();
    }
}

See also

  1. Java - decodeURIComponent equivalent in JavaScript 
  2. JavaScript - encode / escape URL characters

Alternative titles

  1. Java - encode URI component function equivalent in JavaScript
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
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