處理字符串編碼轉換java類

gd7g 9年前發布 | 7K 次閱讀 Java

該字符串處理類包括將ISO-8859-1編碼的字符串轉換成GBK編碼 、對輸入的字符串進行一次編碼轉換,防止SQL注入和驗證URL地址是否存在的方法。

字符串處理類(編碼轉化、SQL注入、URL)

import java.net.HttpURLConnection;
import java.net.URL;

public class StringUtils { public String toGBK(String strvalue) { try { if (strvalue == null) { //當變量strvalue為null時 return ""; //將返回空的字符串 } else { //將字符串轉換為GBK編碼 strvalue = new String(strvalue.getBytes("ISO-8859-1"), "GBK"); return strvalue; //返回轉換后的輸入變量strvalue } } catch (Exception e) { return ""; } }

// 對輸入的字符串進行一次編碼轉換,防止SQL注入
public String StringtoSql(String str) {
    if (str == null) {              //當變量str為null時
        return "";          //返回空的字符串
    } else {
        try {
                                 //將'號轉換化為空格
            str = str.trim().replace('\'', (char) 32);              } catch (Exception e) {
            return "";
        }
    }
    return str;
}
//驗證URL地址是否存在
public int isURLExist(String url){
    int rtn=0;
    try {
        URL u = new URL(url);
        HttpURLConnection urlconn = (HttpURLConnection) u.openConnection();
        int state = urlconn.getResponseCode();
        if (state == 200) {     //表示URL地址存在
            //String succ = urlconn.getURL().toString();
            rtn=1;
        } else {                //表示URL地址不存在
            rtn=0;
        }
    } catch (Exception e) {
        rtn=0;
    }
    return rtn;
}

}</pre>

 本文由用戶 gd7g 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!