2016-11-29 113 views
3

我得到一個例外,第三方庫裏面埋的方式,像這樣的消息:有沒有辦法來添加別名Java的字符集的名字

java.io.UnsupportedEncodingException:BIG-5

我認爲這是因爲Java沒有爲java.nio.charset.Charset定義這個名稱。 Charset.forName("big5")是好的,但Charset.forName("big-5")引發異常。 (所有這些名稱似乎不區分大小寫。)

這與「utf-8」不同,它有一些別名可以更寬容。例如,Charset.forName("utf8")和Charset.forName("utf-8")都可以正常工作。

問題:有沒有辦法添加別名,以便「big-5」映射到「big5」?

+0

是第三方庫的JavaMail任何機會? – dnault

+0

用'private static final Charset BIG5_CHARSET = Charset.forName(「big5」)''在某個地方做一個常量?你再也沒有問題了。還是你說這是你不能控制的代碼? – Tunaki

+0

charset名字從哪裏來?你可以攔截並規範它們嗎? – dnault

回答

2

你可以嘗試mail.mime.contenttypehandler系統屬性:

在某些情況下的JavaMail是無法處理具有無效的Content-Type頭的消息。標題可能有不正確的語法或其他問題。此屬性指定在JavaMail使用它之前將用於清理Content-Type標頭值的類的名稱。該類必須有一個具有此簽名的方法:public static String cleanContentType(MimePart mp,String contentType)每當JavaMail訪問消息的Content-Type頭時,它都會將值傳遞給此方法,並使用返回值。

的一個例子是:

import java.util.Arrays; 
import javax.mail.Session; 
import javax.mail.internet.ContentType; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimePart; 

public class FixEncodingName { 

    public static void main(String[] args) throws Exception { 
     MimeMessage msg = new MimeMessage((Session) null); 
     msg.setText("test", "big-5"); 
     msg.saveChanges(); 
     System.out.println(msg.getContentType()); 
     System.out.println(Arrays.toString(msg.getHeader("Content-Type"))); 
    } 

    public static String cleanContentType(MimePart p, String mimeType) { 
     if (mimeType != null) { 
      String newContentType = mimeType; 
      try { 
       ContentType ct = new ContentType(mimeType); 
       String cs = ct.getParameter("charset"); 
       if ("big-5".equalsIgnoreCase(cs)) { 
        ct.setParameter("charset", "big5"); 
        newContentType = ct.toString(); 
       } 
      } catch (Exception ignore) { 
       newContentType = newContentType.replace("big-5", "big5"); 
      } 

      /*try { //Fix the header in the message. 
       p.setContent(p.getContent(), newContentType); 
       if (p instanceof Message) { 
        ((Message) p).saveChanges(); 
       } 
      } catch (Exception ignore) { 
      }*/ 
      return newContentType; 
     } 
     return mimeType; 
    } 
} 

-Dmail.mime.contenttypehandler=FixEncodingName將輸出運行:

text/plain; charset=big5 
[text/plain; charset=big-5] 
相關問題