Java String Encode encodeIncludingSpecialCharacters(String toEncode)

Here you can find the source of encodeIncludingSpecialCharacters(String toEncode)

Description

Some calls in the Heroku API decode strings in a different way from URLEncoder.

License

Open Source License

Parameter

Parameter Description
config Name/value pairs for a HTTP request.
keys List of keys in the config to encode.

Return

A string representation of encoded parameters.

Declaration

public static String encodeIncludingSpecialCharacters(String toEncode) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Main {
    static final Map<String, String> specialChars = Collections.unmodifiableMap(new HashMap<String, String>() {
        {/*from  ww  w.j  a  va 2  s . co m*/
            put(".", "%2e");
            put("-", "%2d");
            put("*", "%2a");
            put("_", "%5f");
        }
    });

    /**
     * Some calls in the Heroku API decode strings in a different way from URLEncoder. This is a method for handling those
     * special cases. First, urlencode() is called. Then, .-*_ are replaced with their hexadecimal equivalent.
     * @param config Name/value pairs for a HTTP request.
     * @param keys List of keys in the config to encode.
     * @return A string representation of encoded parameters.
     */
    public static String encodeIncludingSpecialCharacters(String toEncode) {
        String encoded = urlencode(toEncode, "Unable to urlencode " + toEncode);
        for (Map.Entry<String, String> s : specialChars.entrySet()) {
            encoded = encoded.replace(s.getKey(), s.getValue());
        }
        return encoded;
    }

    public static String urlencode(String toEncode, String messageIfFails) {
        try {
            return URLEncoder.encode(toEncode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(messageIfFails, e);
        }
    }
}

Related

  1. encodeDownloadFileName(String s)
  2. encodeFilename(final String filename, final String userAgent)
  3. encodeFilename(String filename, String encoding)
  4. encodeFilenameOmittingWhiteSpaces(String filename, String encoding)
  5. encodeForm(Map form)
  6. encodeInternally(String s)
  7. encodeJobHistoryFileName(String logFileName)
  8. encodeMap(Map map, String enc)
  9. encodeName(final String name)