HttpClientUtils(通用)
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.apache.http.Consts;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
/**
*
* @ClassName: HttpsUtils
* @Description: TODO(https post忽略证书请求)
*/
public class HttpClientUtils {
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
static {
try {
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(),
new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);// max connection
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* httpClient post请求
*
* @param url 请求url
* @param header 头部信息
* @param param 请求参数 form提交适用
* @param entity 请求实体 json/xml提交适用
* @return 可能为空 需要处理
* @throws Exception
*/
public static String post(String url, Map<String, String> header, Map<String, String> param, StringEntity entity)
throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
//HttpGet httpPost = new HttpGet(url);//get请求
HttpPost httpPost = new HttpPost(url);//Post请求
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求参数
if (MapUtils.isNotEmpty(param)) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet()) {
// 给参数赋值
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httpPost.setEntity(urlEncodedFormEntity);
}
// 设置实体 优先级高
if (entity != null) {
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(entity);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("状态码:" + statusCode);
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} else {
readHttpResponse(httpResponse);
}
} catch (Exception e) {
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
public static String postXML(String url,String xml){
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try{
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
client = HttpClients.createDefault();
StringEntity entityParams = new StringEntity(xml,"utf-8");
httpPost.setEntity(entityParams);
client = HttpClients.createDefault();
resp = client.execute(httpPost);
String resultMsg = EntityUtils.toString(resp.getEntity(),"utf-8");
return resultMsg;
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(client!=null){
client.close();
}
if(resp != null){
resp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static CloseableHttpClient getHttpClient() throws Exception {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).build();
return httpClient;
}
public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {
StringBuilder builder = new StringBuilder();
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
builder.append("status:" + httpResponse.getStatusLine());
builder.append("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
builder.append("\t" + iterator.next());
}
// 判断响应实体是否为空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
builder.append("response length:" + responseString.length());
builder.append("response content:" + responseString.replace("\r\n", ""));
}
return builder.toString();
}
}
解析XML数据的工具(例子)
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.util.*;
public class AlarmHisXmlFileParse {
public static ArrayList<Map<String,String>> dom4jXml(String interfaceData) {
List<Element> elementList = null;
ArrayList<Map<String,String>> workerList = null;
// ArrayList<List<String>> workerList = null;
try {
SAXReader sr = new SAXReader();
Document document = sr.read(new ByteArrayInputStream(interfaceData.getBytes()));
Element root = document.getRootElement();
elementList = root.elements();
workerList = new ArrayList();
} catch (DocumentException e) {
e.printStackTrace();
}
for (Element e : elementList) {
// 解析标签下一级标签
Element e1 = e.element("ET_PSNDOC");
List<Element> items = e1.elements();
for (int i = 0; i < items.size(); i++) {
Map<String, String> map = new HashMap<>();
Element keyValue = items.get(i);
List<Element> perData = keyValue.elements();
for (int j = 0; j < perData.size(); j++) {
Element perMap = perData.get(j);
map.put(perMap.getName(), perMap.getStringValue());
// list.add(el.getStringValue());
}
workerList.add(map);
}
}
return workerList;
}
}
ASE加密解密(通用)
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
public class AESUtils {
//算法
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
private static String AES_KEY = "cBssbHB3ZA==HKXT";
/**
* aes解密
* @param encrypt 内容
* @return
* @throws Exception
*/
public static String aesDecrypt(String encrypt) {
try {
return aesDecrypt(encrypt, AES_KEY);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* aes加密
* @param content
* @return
* @throws Exception
*/
public static String aesEncrypt(String content) {
try {
return aesEncrypt(content, AES_KEY);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 将byte[]转为各种进制的字符串
* @param bytes byte[]
* @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制
* @return 转换后的字符串
*/
public static String binary(byte[] bytes, int radix){
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
}
/**
* base 64 encode
* @param bytes 待编码的byte[]
* @return 编码后的base 64 code
*/
public static String base64Encode(byte[] bytes){
return Base64.encodeBase64String(bytes);
}
/**
* base 64 decode
* @param base64Code 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception
*/
public static byte[] base64Decode(String base64Code) throws Exception{
return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
}
/**
* AES加密
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的byte[]
* @throws Exception
*/
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
/**
* AES加密为base 64 code
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的base 64 code
* @throws Exception
*/
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
/**
* AES解密
* @param encryptBytes 待解密的byte[]
* @param decryptKey 解密密钥
* @return 解密后的String
* @throws Exception
*/
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
/**
* 将base 64 code AES解密
* @param encryptStr 待解密的base 64 code
* @param decryptKey 解密密钥
* @return 解密后的string
* @throws Exception
*/
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
/**
* 测试
* 前端js将参数加密提交到后台如何解密
* 首先获取服务端的私钥:将客户端的公钥加密后获得的结果
* 通过服务端的私钥和客户端传递的加密字符串即可实现解密
*/
public static void main(String[] args) throws Exception {
String content = "456";
System.out.println("加密前:" + content);
System.out.println("加密密钥和解密密钥:" + AES_KEY);
String encrypt = aesEncrypt(content, AES_KEY);
System.out.println("加密后:" + encrypt);
String decrypt = aesDecrypt(encrypt, AES_KEY);
System.out.println("解密后:" + decrypt);
//js加密后的字符串: lkqsgKHH7OkhIa0tISMtuQ==
}
}
字符串处理工具(通用)
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串处理工具类
* @author ziyuzhang
*
*/
public class StringUtil {
public StringUtil() {
}
/**
* 得到字符串中某个字符的个数
* @param str 字符串
* @param c 字符
* @return
*/
public static final int getCharnum(String str,char c){
int num = 0;
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++)
{
if(c == chars[i])
{
num++;
}
}
return num;
}
/**
* 返回yyyymm
* @param aDate
* @return
*/
public static final String getYear_Month(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";
if (aDate != null) {
df = new SimpleDateFormat("yyyyMM");
returnValue = df.format(aDate);
}
return (returnValue);
}
/**
* hxw 返回当前年
*
* @return
*/
public static String getYear() {
Calendar calendar = Calendar.getInstance();
return String.valueOf(calendar.get(1));
}
/**
* hxw 返回当前月
*
* @return
*/
public static String getMonth() {
Calendar calendar = Calendar.getInstance();
String temp = String.valueOf(calendar.get(2) + 1);
if (temp.length() < 2)
temp = "0" + temp;
return temp;
}
/**
* 按长度分割字符串
*
* @param content
* @param len
* @return
*/
public static String[] split(String content, int len) {
if (content == null || content.equals("")) {
return null;
}
int len2 = content.length();
if (len2 <= len) {
return new String[] { content };
} else {
int i = len2 / len + 1;
System.out.println("i:" + i);
String[] strA = new String[i];
int j = 0;
int begin = 0;
int end = 0;
while (j < i) {
begin = j * len;
end = (j + 1) * len;
if (end > len2)
end = len2;
strA[j] = content.substring(begin, end);
// System.out.println(strA[j]+"<br/>");
j = j + 1;
}
return strA;
}
}
public static boolean emailFormat(String email)
{
boolean tag = true;
final String pattern1 = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
final Pattern pattern = Pattern.compile(pattern1);
final Matcher mat = pattern.matcher(email);
if (!mat.find()) {
tag = false;
}
return tag;
}
/**
* 验证是不是EMAIL
* @param email
* @return
*/
public static boolean isEmail(String email) {
boolean retval = false;
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
retval = matcher.matches();
return retval;
}
/**
* 验证汉字为true
* @param s
* @return
*/
public static boolean isLetterorDigit(String s) {
if (s.equals("") || s == null) {
return false;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isLetterOrDigit(s.charAt(i))) {
// if (!Character.isLetter(s.charAt(i))){
return false;
}
}
// Character.isJavaLetter()
return true;
}
/**
* 判断某字符串是否为null,如果长度大于256,则返回256长度的子字符串,反之返回原串
* @param str
* @return
*/
public static String checkStr(String str){
if(str==null){
return "";
}else if(str.length()>256){
return str.substring(256);
}else{
return str;
}
}
/**
* 验证是不是Int
* validate a int string
* @param str
* the Integer string.
* @return true if the str is invalid otherwise false.
*/
public static boolean validateInt(String str) {
if (str == null || str.trim().equals(""))
return false;
char c;
for (int i = 0, l = str.length(); i < l; i++) {
c = str.charAt(i);
if (!((c >= '0') && (c <= '9')))
return false;
}
return true;
}
/**
* 字节码转换成16进制字符串 内部调试使用
*
* @param b
* @return
*/
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + ":";
}
return hs.toUpperCase();
}
/**
* 字节码转换成自定义字符串 内部调试使用
*
* @param b
* @return
*/
public static String byte2string(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
// if (n<b.length-1) hs=hs+":";
}
return hs.toUpperCase();
}
public static byte[] string2byte(String hs) {
byte[] b = new byte[hs.length() / 2];
for (int i = 0; i < hs.length(); i = i + 2) {
String sub = hs.substring(i, i + 2);
byte bb = new Integer(Integer.parseInt(sub, 16)).byteValue();
b[i / 2] = bb;
}
return b;
}
/**
* 验证字符串是否为空
* @param param
* @return
*/
public static boolean empty(String param) {
return param == null || param.trim().length() < 1;
}
// 验证英文字母或数据
public static boolean isLetterOrDigit(String str) {
java.util.regex.Pattern p = null; // 正则表达式
java.util.regex.Matcher m = null; // 操作的字符串
boolean value = true;
try {
p = java.util.regex.Pattern.compile("[^0-9A-Za-z]");
m = p.matcher(str);
if (m.find()) {
value = false;
}
} catch (Exception e) {
}
return value;
}
/**
* 验证是否是小写字符串
*/
@SuppressWarnings("unused")
private static boolean isLowerLetter(String str) {
java.util.regex.Pattern p = null; // 正则表达式
java.util.regex.Matcher m = null; // 操作的字符串
boolean value = true;
try {
p = java.util.regex.Pattern.compile("[^a-z]");
m = p.matcher(str);
if (m.find()) {
value = false;
}
} catch (Exception e) {
}
return value;
}
/**
* 判断一个字符串是否都为数字
* @param strNum
* @return
*/
public static boolean isDigit(String strNum) {
return strNum.matches("[0-9]{1,}");
}
/**
* 判断一个字符串是否都为数字
* @param strNum
* @return
*/
public static boolean isDigit2(String strNum) {
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher((CharSequence) strNum);
return matcher.matches();
}
/**
* 截取数字
* @param content
* @return
*/
public static String getNumbers(String content) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}
/**
* 截取非数字
* @param content
* @return
*/
public static String splitNotNumber(String content) {
Pattern pattern = Pattern.compile("\\D+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}
public static String encode(String str, String code) {
try {
return URLEncoder.encode(str, code);
} catch (Exception ex) {
ex.fillInStackTrace();
return "";
}
}
public static String decode(String str, String code) {
try {
return URLDecoder.decode(str, code);
} catch (Exception ex) {
ex.fillInStackTrace();
return "";
}
}
public static String nvl(String param) {
return param != null ? param.trim() : "";
}
public static String nvl(Object param) {
return param != null ? param.toString().trim() : "";
}
public static int parseInt(String param, int d) {
int i = d;
try {
i = Integer.parseInt(param);
} catch (Exception e) {
}
return i;
}
public static int parseInt(String param) {
return parseInt(param, 0);
}
public static long parseLong(String param) {
long l = 0L;
try {
l = Long.parseLong(param);
} catch (Exception e) {
}
return l;
}
public static double parseDouble(String param) {
return parseDouble(param, 1.0);
}
public static double parseDouble(String param, double t) {
double tmp = 0.0;
try {
tmp = Double.parseDouble(param.trim());
} catch (Exception e) {
tmp = t;
}
return tmp;
}
public static boolean parseBoolean(String param) {
if (empty(param))
return false;
switch (param.charAt(0)) {
case 49: // '1'
case 84: // 'T'
case 89: // 'Y'
case 116: // 't'
case 121: // 'y'
return true;
}
return false;
}
/**
* public static String replace(String mainString, String oldString, String
* newString) { if(mainString == null) return null; int i =
* mainString.lastIndexOf(oldString); if(i < 0) return mainString;
* StringBuffer mainSb = new StringBuffer(mainString); for(; i >= 0; i =
* mainString.lastIndexOf(oldString, i - 1)) mainSb.replace(i, i +
* oldString.length(), newString);
*
* return mainSb.toString(); }
*
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static final String[] split(String str, String delims) {
StringTokenizer st = new StringTokenizer(str, delims);
ArrayList list = new ArrayList();
for (; st.hasMoreTokens(); list.add(st.nextToken()))
;
return (String[]) list.toArray(new String[list.size()]);
}
public static String substring(String str, int length) {
if (str == null)
return null;
if (str.length() > length)
return (str.substring(0, length - 2) + "...");
else
return str;
}
public static boolean validateDouble(String str) throws RuntimeException {
if (str == null)
// throw new RuntimeException("null input");
return false;
char c;
int k = 0;
for (int i = 0, l = str.length(); i < l; i++) {
c = str.charAt(i);
if (!((c >= '0') && (c <= '9')))
if (!(i == 0 && (c == '-' || c == '+')))
if (!(c == '.' && i < l - 1 && k < 1))
// throw new RuntimeException("invalid number");
return false;
else
k++;
}
return true;
}
public static boolean validateMobile(String str, boolean includeUnicom) {
if (str == null || str.trim().equals(""))
return false;
str = str.trim();
if (str.length() != 11 || !validateInt(str))
return false;
if (includeUnicom
&& (str.startsWith("130") || str.startsWith("133") || str.startsWith("131")))
return true;
if (!(str.startsWith("139") || str.startsWith("138") || str.startsWith("137")
|| str.startsWith("136") || str.startsWith("135")))
return false;
return true;
}
public static boolean validateMobile(String str) {
return validateMobile(str, false);
}
/**
* delete file
*
* @param fileName
* @return -1 exception,1 success,0 false,2 there is no one directory of the
* same name in system
*/
public static int deleteFile(String fileName) {
File file = null;
int returnValue = -1;
try {
file = new File(fileName);
if (file.exists())
if (file.delete())
returnValue = 1;
else
returnValue = 0;
else
returnValue = 2;
} catch (Exception e) {
System.out.println("Exception:e=" + e.getMessage());
} finally {
file = null;
// return returnValue;
}
return returnValue;
}
public static String gbToIso(String s) throws UnsupportedEncodingException {
return covertCode(s, "GB2312", "ISO8859-1");
}
public static String covertCode(String s, String code1, String code2)
throws UnsupportedEncodingException {
if (s == null)
return null;
else if (s.trim().equals(""))
return "";
else
return new String(s.getBytes(code1), code2);
}
public static String transCode(String s0) throws UnsupportedEncodingException {
if (s0 == null || s0.trim().equals(""))
return null;
else {
s0 = s0.trim();
return new String(s0.getBytes("GBK"), "ISO8859-1");
}
}
/**
* 编码转换
* @param s
* @return
*/
public static String GBToUTF8(String s) {
try {
StringBuffer out = new StringBuffer("");
byte[] bytes = s.getBytes("unicode");
for (int i = 2; i < bytes.length - 1; i += 2) {
out.append("\\u");
String str = Integer.toHexString(bytes[i + 1] & 0xff);
for (int j = str.length(); j < 2; j++) {
out.append("0");
}
out.append(str);
String str1 = Integer.toHexString(bytes[i] & 0xff);
for (int j = str1.length(); j < 2; j++) {
out.append("0");
}
out.append(str1);
}
return out.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings("unused")
public static final String[] replaceAll(String[] obj, String oldString, String newString) {
if (obj == null) {
return null;
}
int length = obj.length;
String[] returnStr = new String[length];
String str = null;
for (int i = 0; i < length; i++) {
returnStr[i] = replaceAll(obj[i], oldString, newString);
}
return returnStr;
}
/**
* 字符串全文替换
* @param s0
* @param oldstr
* @param newstr
* @return
*/
public static String replaceAll(String s0, String oldstr, String newstr) {
if (s0 == null || s0.trim().equals(""))
return null;
StringBuffer sb = new StringBuffer(s0);
int begin = 0;
// int from = 0;
begin = s0.indexOf(oldstr);
while (begin > -1) {
sb = sb.replace(begin, begin + oldstr.length(), newstr);
s0 = sb.toString();
begin = s0.indexOf(oldstr, begin + newstr.length());
}
return s0;
}
public static String toHtml(String str) {
String html = str;
if (str == null || str.length() == 0) {
return str;
}
html = replaceAll(html, "&", "&");
html = replaceAll(html, "<", "<");
html = replaceAll(html, ">", ">");
html = replaceAll(html, "\r\n", "\n");
html = replaceAll(html, "\n", "<br>\n");
html = replaceAll(html, "\t", " ");
html = replaceAll(html, " ", " ");
return html;
}
/**
* 字符串替换
* @param line
* @param oldString
* @param newString
* @return
*/
public static final String replace(String line, String oldString, String newString) {
if (line == null) {
return null;
}
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
public static final String replaceIgnoreCase(String line, String oldString, String newString) {
if (line == null) {
return null;
}
String lcLine = line.toLowerCase();
String lcOldString = oldString.toLowerCase();
int i = 0;
if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
/**
* 标签转义
* @param input
* @return
*/
public static final String escapeHTMLTags(String input) {
// Check if the string is null or zero length -- if so, return
// what was sent in.
if (input == null || input.length() == 0) {
return input;
}
// Use a StringBuffer in lieu of String concatenation -- it is
// much more efficient this way.
StringBuffer buf = new StringBuffer(input.length());
char ch = ' ';
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
if (ch == '<') {
buf.append("<");
} else if (ch == '>') {
buf.append(">");
} else {
buf.append(ch);
}
}
return buf.toString();
}
/**
* Returns a random String of numbers and letters of the specified length.
* The method uses the Random class that is built-in to Java which is
* suitable for low to medium grade security uses. This means that the
* output is only pseudo random, i.e., each number is mathematically
* generated so is not truly random.
* <p>
*
* For every character in the returned String, there is an equal chance that
* it will be a letter or number. If a letter, there is an equal chance that
* it will be lower or upper case.
* <p>
*
* The specified length must be at least one. If not, the method will return
* null.
*
* @param length
* the desired length of the random String to return.
* @return a random String of numbers and letters of the specified length.
*/
private static Random randGen = null;
private static Object initLock = new Object();
private static char[] numbersAndLetters = null;
public static final String randomString(int length) {
if (length < 1) {
return null;
}
// Init of pseudo random number generator.
if (randGen == null) {
synchronized (initLock) {
if (randGen == null) {
randGen = new Random();
// Also initialize the numbersAndLetters array
numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
}
}
}
// Create a char buffer to put random letters and numbers in.
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}
/**
* 固定长度字符串截取
* @param content
* @param i
* @return
*/
public static String getSubstring(String content, int i) {
int varsize = 10;
String strContent = content;
if (strContent.length() < varsize + 1) {
return strContent;
} else {
int max = (int) Math.ceil((double) strContent.length() / varsize);
if (i < max - 1) {
return strContent.substring(i * varsize, (i + 1) * varsize);
} else {
return strContent.substring(i * varsize);
}
}
}
/**
* 日期转String
* @param pattern
* @return
*/
public static String now(String pattern) {
return dateToString(new Date(), pattern);
}
public static String dateToString(Date date, String pattern) {
if (date == null) {
return "";
} else {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
}
public static synchronized String getNow() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(new Date());
}
/**
* String转Date
* @param strDate
* @param pattern
* @return
* @throws ParseException
*/
public static java.sql.Date stringToDate(String strDate, String pattern) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse(strDate);
long lngTime = date.getTime();
return new java.sql.Date(lngTime);
}
public static java.util.Date stringToUtilDate(String strDate, String pattern)
throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.parse(strDate);
}
public static String formatHTMLOutput(String s) {
if (s == null)
return null;
if (s.trim().equals(""))
return "";
String formatStr;
formatStr = replaceAll(s, " ", " ");
formatStr = replaceAll(formatStr, "\n", "<br />");
return formatStr;
}
/*
* 4舍5入 @param num 要调整的数 @param x 要保留的小数位
*/
public static double myround(double num, int x) {
BigDecimal b = new BigDecimal(num);
return b.setScale(x, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/*
* public static String getSubstring(String content,int i){ int varsize=10;
* String strContent=content; if(strContent.length()<varsize+1){ return
* strContent; }else{ int
* max=(int)Math.ceil((double)strContent.length()/varsize); if(i<max-1){
* return strContent.substring(i*varsize,(i+1)*varsize); }else{ return
* strContent.substring(i*varsize); } } }
*/
/**
* liuqs
*
* @param param
* @param d
* @return
*/
public static int parseLongInt(Long param, int d) {
int i = d;
try {
i = Integer.parseInt(String.valueOf(param));
} catch (Exception e) {
}
return i;
}
public static int parseLongInt(Long param) {
return parseLongInt(param, 0);
}
public static String returnString(Object obj) {
if (obj == null) {
return "";
} else {
return obj.toString();
}
}
/**
* 修改敏感字符编码
* @param value
* @return
*/
public static String htmlEncode(String value){
String re[][] = {{"<","<"},
{">",">"},
{"\"","""},
{"\\′","´"},
{"&","&"}
};
for(int i=0; i<4; i++){
value = value.replaceAll(re[i][0], re[i][1]);
}
return value;
}
/**
* 防SQL注入
*
* @param str
* @return
*/
public static boolean sql_inj(String str) {
String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
String inj_stra[] = inj_str.split("|");
for (int i=0 ; i < inj_stra.length ; i++ )
{
if (str.indexOf(inj_stra[i])>=0)
{
return true;
}
}
return false;
}
}
JSON装换工具(通用)
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* @Description: JSON序列化
*/
public class JSONUtils {
private static Logger logger = LoggerFactory.getLogger(JSONUtils.class);
private static ObjectMapper objectMapper = new ObjectMapper();
private static ObjectMapper objectMapperNonNull = new ObjectMapper();
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
objectMapperNonNull.setSerializationInclusion(Include.NON_NULL);
}
/**
* 将对象转换成json字符串。
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
if (e.getMessage().contains("org.springframework.validation.BindingResult.themeScreen")){
}else{
e.printStackTrace();
}
}
return null;
}
/**
* 将json结果集转化为对象
*/
public static <T> T jsonToPoJo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
public static <T> T jsonToList(String jsonData, TypeReference<T> typeReference) throws JsonParseException, JsonMappingException, IOException {
return MAPPER.readValue(jsonData, typeReference);
}
/**
* @Description: 将json字符串读为java对象
*/
public static <T> T read(String content, Class<T> valueType) {
try {
return objectMapper.readValue(content, valueType);
} catch (Exception e) {
logger.error("error on read json [" + content + "]", e);
throw new RuntimeException("error on read json");
}
}
/**
* @Description: 反序列化为Map
* @date 2015年7月14日上午11:22:03
* @version 2.2.0
*/
public static Map<?,?> readAsMap(String content) {
return read(content, Map.class);
}
/**
* @Description: 将java对象写为json字符串
*/
public static String write(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
logger.error("error on write json", e);
throw new RuntimeException("error on write json");
}
}
public static String writeExcludeNull(Object value) {
try {
return objectMapperNonNull.writeValueAsString(value);
} catch (JsonProcessingException e) {
logger.error("error on write json", e);
throw new RuntimeException("error on write json");
}
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @return
*/
@SuppressWarnings("rawtypes")
public static List<Object> getDTOArray(String jsonString, Class clazz){
List<Object> list = new ArrayList<Object>();
JSONArray array = JSONArray.fromObject(jsonString);
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
list.add(JSONObject.toBean(jsonObject, clazz));
}
return list;
}
public static Map<String, Object> jsonToMap(String jsonString) throws UnsupportedEncodingException {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject json = JSONObject.fromObject(jsonString);
for (Object k : json.keySet()) {
Object v = json.get(k);
try {
map.put(k.toString(),java.net.URLDecoder.decode(v.toString(), "UTF-8"));
} catch (Exception e) {
map.put(k.toString(),v.toString());
}
}
return map;
}
public static Map<String, String> jsonToStringMap(String jsonString)throws UnsupportedEncodingException {
Map<String, String> map = new HashMap<String, String>();
JSONObject json = JSONObject.fromObject(jsonString);
for (Object k : json.keySet()) {
Object v = json.get(k);
try {
map.put(k.toString(),java.net.URLDecoder.decode(v.toString(), "UTF-8"));
} catch (Exception e) {
map.put(k.toString(),v.toString());
}
}
return map;
}
public static LinkedHashMap<String, String> jsonToStringLinkedMap(String jsonString)throws UnsupportedEncodingException {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
JSONObject json = JSONObject.fromObject(jsonString);
for (Object k : json.keySet()) {
Object v = json.get(k);
try {
map.put(k.toString(),java.net.URLDecoder.decode(v.toString(), "UTF-8"));
} catch (Exception e) {
map.put(k.toString(),v.toString());
}
}
return map;
}
/**
* 将json转化为实体POJO
* @param jsonStr
* @param obj
* @return
*/
@SuppressWarnings("deprecation")
public static<T> Object JSONToObj(String jsonStr,Class<T> obj) {
T t = null;
try {
org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper();
//设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
objectMapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
t = objectMapper.readValue(jsonStr, obj);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
public static void main(String[] args) {
String se = "[{'adverbialId':1,'nameId':'chan24_vehhvdcdchvsidevolv','typeId':'DCDC','valueId':'123123'}]";
List<Object> ob = getDTOArray(se, Map.class);
for (Object object : ob) {
Map<String,Object> obMap = (Map<String,Object>) object;
for(Map.Entry<String,Object> entry:obMap.entrySet())
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
/**
* json 转 List<T>
*/
public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> ts = (List<T>) com.alibaba.fastjson.JSONArray.parseArray(jsonString, clazz);
return ts;
}
}