使用Java的对UTF8URL进行编码方式

public class Test {
    /**
     * Utf8URL编码
     * @param s
     * @return
     */
    public static final String Utf8URLencode(String text) {
      StringBuffer result = new StringBuffer();
      for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c >= 0 && c <= 255) {
          result.append(c);
        }else {
          byte[] b = new byte[0];
          try {
            b = Character.toString(c).getBytes("UTF-8");
          }catch (Exception ex) {
          }
          for (int j = 0; j < b.length; j++) {
            int k = b[j];
            if (k < 0) k += 256;
            result.append("%" + Integer.toHexString(k).toUpperCase());
          }
        }
      }
      return result.toString();
    }
    public static void main(String[] args) {

    String   url = "http://localhost:8080/upload_file/20170609162432827/help2.pdf";

    String   url2 = "http://localhost:8080/upload_file/20170609162432827/五杀.pdf";

          System.out.println(Utf8URLencode(url));   //如果是中文就默认转为url的编码格式,和浏览器相同,如果没有中文就不做转换

    }

  
}

猜你喜欢

转载自blog.csdn.net/qq_34354426/article/details/73467734
今日推荐