当前位置:   article > 正文

JAVA base64 工具类_java base64工具类

java base64工具类
  1. import java.io.UnsupportedEncodingException;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;
  5. import java.util.SortedMap;
  6. public class Base64Util {
  7. private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  8. public String getBase64Str(SortedMap<Object, Object> parameters) throws UnsupportedEncodingException {
  9. StringBuffer sb = new StringBuffer();
  10. Set es = parameters.entrySet();
  11. Iterator it = es.iterator();
  12. while (it.hasNext())
  13. {
  14. Map.Entry entry = (Map.Entry) it.next();
  15. String k = (String) entry.getKey();
  16. Object v = entry.getValue();
  17. if (null != v && !"".equals(v))
  18. {
  19. sb.append(k + "=" + v + "&");
  20. }
  21. }
  22. sb.deleteCharAt(sb.lastIndexOf("&"));
  23. return encode(sb.toString().getBytes("UTF-8")).replaceAll(" ", "");
  24. }
  25. public static String encode(byte[] data)
  26. {
  27. int start = 0;
  28. int len = data.length;
  29. StringBuffer buf = new StringBuffer(data.length * 3 / 2);
  30. int end = len - 3;
  31. int i = start;
  32. int n = 0;
  33. while (i <= end)
  34. {
  35. int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff);
  36. buf.append(legalChars[(d >> 18) & 63]);
  37. buf.append(legalChars[(d >> 12) & 63]);
  38. buf.append(legalChars[(d >> 6) & 63]);
  39. buf.append(legalChars[d & 63]);
  40. i += 3;
  41. if (n++ >= 14)
  42. {
  43. n = 0;
  44. buf.append(" ");
  45. }
  46. }
  47. if (i == start + len - 2)
  48. {
  49. int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);
  50. buf.append(legalChars[(d >> 18) & 63]);
  51. buf.append(legalChars[(d >> 12) & 63]);
  52. buf.append(legalChars[(d >> 6) & 63]);
  53. buf.append("=");
  54. }
  55. else if (i == start + len - 1)
  56. {
  57. int d = (((int) data[i]) & 0x0ff) << 16;
  58. buf.append(legalChars[(d >> 18) & 63]);
  59. buf.append(legalChars[(d >> 12) & 63]);
  60. buf.append("==");
  61. }
  62. return buf.toString();
  63. }
  64. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/202960
推荐阅读
相关标签
  

闽ICP备14008679号