Java file download file name garble solution

  • 2020-04-01 01:38:25
  • OfStack


public static String toUtf8String(String s) { 

             StringBuffer sb = new StringBuffer(); 
             for (int i = 0; i < s.length(); i++) { 
                 char c = s.charAt(i); 
                 if (c >= 0 && c <= 255) { 
                     sb.append(c); 
                 } else { 
                     byte[] b; 
                     try { 
                         b = Character.toString(c).getBytes("utf-8"); 
                     } catch (Exception ex) { 
                         exceptionUtil.error(" Converts the Chinese character in the file name to UTF8 Error in string encoding, the input string is: " + s); 
                         b = new byte[0]; 
                     } 
                     for (int j = 0; j < b.length; j++) { 
                         int k = b[j]; 
                         if (k < 0) 
                             k += 256; 
                         sb.append("%" + Integer.toHexString(k).toUpperCase()); 
                     } 
                 } 
             } 
             return sb.toString(); 
         } 

          
         public static String toUtf8String(HttpServletRequest request, String s) { 
             String agent = request.getHeader("User-Agent"); 
             try { 
                 boolean isFireFox = (agent != null && agent.toLowerCase().indexOf("firefox") != -1); 
                 if (isFireFox) { 
                     s = new String(s.getBytes("UTF-8"), "ISO8859-1"); 
                 } else { 
                     s = StringUtil.toUtf8String(s); 
                     if ((agent != null && agent.indexOf("MSIE") != -1)) { 
                         // see http://support.microsoft.com/default.aspx?kbid=816868 
                         if (s.length() > 150) { 
                             //The possible code based on the request locale
                             s = new String(s.getBytes("UTF-8"), "ISO8859-1"); 
                         } 
                     } 
                 } 
             } catch (UnsupportedEncodingException e) { 
                 e.printStackTrace(); 
             } 
             return s; 
         }

Related articles: