Java URL Encode encode(String value, String encoding)

Here you can find the source of encode(String value, String encoding)

Description

Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

License

Apache License

Parameter

Parameter Description
value <code>String</code> to be translated.
encoding The name of a supported character encoding</a>.

Exception

Parameter Description
IllegalArgumentException If the named encoding is not supported

Return

the translated String.

Declaration

public static String encode(String value, String encoding) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.net.URLEncoder;

public class Main {
    /**/* w  ww  . j a va 2  s  .c  o  m*/
     *
     */
    private static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * Translates a string into <code>application/x-www-form-urlencoded</code> format using a specific encoding scheme.
     * This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.
     * <p/>
     * <em><strong>Note:</strong> The <a href= "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars"> World
     * Wide Web Consortium Recommendation</a> states that UTF-8 should be used. Not doing so may introduce
     * incompatibilites.</em>
     *
     * @param value
     *         <code>String</code> to be translated.
     * @param encoding
     *         The name of a supported character encoding</a>.
     * @return the translated <code>String</code>.
     * @throws IllegalArgumentException
     *         If the named encoding is not supported
     * @see URLDecoder#decode(java.lang.String, java.lang.String)
     * @since 1.4
     */
    public static String encode(String value, String encoding) throws IllegalArgumentException {
        String encodedValue = null;
        try {
            encodedValue = URLEncoder.encode(value, encoding);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
        return encodedValue;
    }

    /**
     * {@link #encode(String, String)} with "UTF-8" encoding
     *
     * @param value
     *         the <code>String</code> to decode
     * @return the newly encoded <code>String</code>
     */
    public static String encode(String value) {
        return encode(value, DEFAULT_ENCODING);
    }
}

Related

  1. encode(String value)
  2. encode(String value)
  3. encode(String value)
  4. encode(String value)
  5. encode(String value, String charset)
  6. encodeArray(final String[] val)
  7. encodeForUrl(final String s)
  8. encodeSrcUrl(String fullUri)
  9. encodeStringURL(String str)