java判斷字串是否為亂碼
阿新 • • 發佈:2018-11-13
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
專案中有一個功能 在IE中GET方式提交會產生亂碼 但有兩個入口都會走這同一段程式碼
固不能直接轉碼,所以要進行判斷傳過來的該值是不是亂碼可用以下方式驗證:
java.nio.charset.Charset.forName("GBK" ).newEncoder().canEncode("測試") //判斷是不是GBK編碼 即是否亂碼
//使用request.getQueryString()獲取通過URL傳過來的值 有可能是亂碼 如:q=éæ¥String s = request.getQueryString(); if(s!=null){ if(!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(s))){ try { s = new String(request.getQueryString().getBytes("ISO-8859-1" ),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
PS:網上有資料用正則驗證,看著挺複雜的。現以上方式暫時可用。