Java String Encode encodeUTF8(String input, boolean keepSpaces)

Here you can find the source of encodeUTF8(String input, boolean keepSpaces)

Description

Encod input as UTF-8 while converting %20 (space) to a space

License

Open Source License

Parameter

Parameter Description
input Input
keepSpaces <code>true</code> if spaces should be preserved, <code>false</code> otherwise

Return

Input encoded using UTF-8 or null if input was null

Declaration

public static String encodeUTF8(String input, boolean keepSpaces) 

Method Source Code

//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Main {
    public static final String UTF_8 = "UTF-8";

    /**/* w ww  .  jav  a2 s .c om*/
     * Encode input using UTF-8
     *
     * @param input Input
     * @return Input encoded using UTF-8 or <code>null</code> if input was null
     */
    public static String encodeUTF8(String input) {
        return encodeUTF8(input, false);
    }

    /**
     * Encod input as UTF-8 while converting %20 (space) to a space
     *
     * @param input Input
     * @param keepSpaces <code>true</code> if spaces should be preserved, <code>false</code> otherwise
     * @return Input encoded using UTF-8 or <code>null</code> if input was null
     */
    public static String encodeUTF8(String input, boolean keepSpaces) {
        if (input == null) {
            return null;
        }

        String encodedInput;

        try {
            encodedInput = URLEncoder.encode(input, UTF_8);
        } catch (UnsupportedEncodingException e) {
            return input;
        }

        if (keepSpaces) {
            encodedInput = encodedInput.replaceAll("[+]", " ");
        }

        return encodedInput;
    }
}

Related

  1. encodeThoroughly(String s)
  2. encodeToFlex(Object o)
  3. encodeToForm(Map msg)
  4. encodeToString(String s)
  5. encodeURNComponent(String value)
  6. encodeUTF8(String s)
  7. encodeUTF8(String s)
  8. encodeValue(String dirtyValue)
  9. encodeValue(String str)