Java tutorial
//package com.java2s; //License from project: Apache License import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class Main { public static String utf8Encode(String str) { if (!isEmpty(str) && str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UnsupportedEncodingException occurred. ", e); } } return str; } /** * encoded in utf-8, if exception, return defultReturn * * @param str * @param defultReturn * @return */ public static String utf8Encode(String str, String defultReturn) { if (!isEmpty(str) && str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { return defultReturn; } } return str; } public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } }