版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
文章目录
非对称加密验签工具类
支持 SHA1withRSA、SHA256withRSA、SHA1withDSA
本类需要工具类支持:https://mp.csdn.net/mdeditor/84635754 非对称加密基础工具类
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import org.apache.commons.codec.binary.Base64;
/**
* 非对称加密验签工具类
* jie.wu
* 本类需要工具类支持:https://mp.csdn.net/mdeditor/84635754 非对称加密基础工具类
* /
public class SignatureUtil {
//下面提供一个 SHA1withRSA 的签名和验证例子
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
//RSA 1024 私钥
String privateBase64Str="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALfXBP15PeOBS0h20hXZtIyeKiWx9py+VWagxfY2QvWH/+wu8xMpt0WFNWG6nS3ju9u2cViRQUYjRD5kz8hpRy8NdVoV/kbkZeK3LUqZs5/cb378uQTO3LWfOQJFBMz6ll2CXWEjEHGdxzj6iRjFYoC4VS+DDTGO+6iHmYSpP3/1AgMBAAECgYB94VqGYZ1yCZdOACZsVczeOHLtqsUNoPqDMnU62P7SdxRTWfaRWZAnp0XdLFXyFS0ODgfguF10tDNHceog9Y2KS3fHJK3JIur1Y55BqKzLlQlrAWpziaigEw+xJqiO+U67gomlCLTS6kYhFvPGXip3wOctvEh8yG1RX3exTmiVwQJBAPlWm6Aok86vHsBS8Znev1VV9nsSexrJXXkkdHv2ux2JSwQi/WNwWloolUtHFCGcyVmhNEmB7sSbR7/hmaKhiNECQQC8wGySaQIessawFnN/i+xmdoO0OeLCaR9MEce3B5dfRlTq37cfCbGCGnhSi5iRzx4/PHJGNoLPP2xFTVZ5VY3lAkA2rsTgwiVwbb2bxlUQPubNa1XsNehjvofOeq1FRp5Q4vxdwuK5fTmDjmT3pnYGzSDnlFAoUuOvoLKCpZKRNUYRAkALj4WW2hOlKbH9qwJb94f9JpkeesUmvyWJlTU0QqTE0xv0XstqfT+ABnsEI0Su+Y6StPMS1dfhNbM982Sufcz5AkB8OC1vMSQ0oYKxgS3nvNyNlTEjcveJALQAgU7vpSiA0/5LdwUFb7gCKQDL6pq8ySbZ4NV/U5xDVoBzsa5AIEVK";
//RSA 1024 公钥
String publicBase64Str="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC31wT9eT3jgUtIdtIV2bSMniolsfacvlVmoMX2NkL1h//sLvMTKbdFhTVhup0t47vbtnFYkUFGI0Q+ZM/IaUcvDXVaFf5G5GXity1KmbOf3G9+/LkEzty1nzkCRQTM+pZdgl1hIxBxncc4+okYxWKAuFUvgw0xjvuoh5mEqT9/9QIDAQAB";
//非对称加密算法,如 RSA
String algorithm="RSA";
//非对称加密验签规则
String sign_algorithm="SHA1withRSA";
//待加密字符串:
String str="method=info.auth#app_id=2138&sign_type=RSA×tamp=2013-01-0108:08:08";
//字符编码 方式
String charset="utf8";
//获取私钥
PrivateKey privateKey=AsymmetricEncryptionUtil.restorePrivateKey(privateBase64Str,algorithm,charset);
//获取公钥
PublicKey publicKey=AsymmetricEncryptionUtil.restorePublicKey(publicBase64Str,algorithm,charset);
//使用私钥计算签名
String signStr=signatureSign(sign_algorithm,charset,str,privateKey);
System.out.println("signStr="+signStr);
//使用公钥验证签名
System.out.println(signatureVerify(sign_algorithm,charset,str,signStr,publicKey));
}
/**
* 非对称加密签名-签名计算方法
* @param algorithm 签名算法,如 SHA1withRSA
* <ul>
* <li>{@code SHA1withDSA}</li>
* <li>{@code SHA1withRSA}</li>
* <li>{@code SHA256withRSA}</li>
* </ul>
* @param charset 字符编码格式,如 utf8、gbk
* @param str 原字符串
* @param privateKey 非对称加密 私钥
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
public static String signatureSign(String algorithm,String charset,String str,PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
//指定签名算法如 SHA1withRSA
Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
//注意编码格式 utf8、gbk
signature.update(str.getBytes(charset));
//结果转 Base64,注意编码格式 utf8、gbk
String signStr=new String(Base64.encodeBase64(signature.sign()),charset);
return signStr;
}
/**
* 非对称加密签名-签名校验方法,验证通过返回 true
* @param algorithm 签名算法,如 SHA1withRSA
* <ul>
* <li>{@code SHA1withDSA}</li>
* <li>{@code SHA1withRSA}</li>
* <li>{@code SHA256withRSA}</li>
* </ul>
* @param charset 字符编码格式,如 utf8、gbk
* @param str 原字符串
* @param signStr 待校验签名内容
* @param publicKey 非对称加密 公钥
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
public static boolean signatureVerify(String algorithm,String charset,String str,String signStr,PublicKey publicKey) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, UnsupportedEncodingException {
//指定签名算法如 SHA1withRSA
Signature signature = Signature.getInstance(algorithm);
signature.initVerify(publicKey);
//加密前的文本
signature.update(str.getBytes(charset));
//比较 私钥 的加密结果
return signature.verify(Base64.decodeBase64(signStr.getBytes()));
}
}
非对称加密基础工具类
可以根据不同的入参,支持 RSA\DSA等非对称加密算法
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* 非对称加密 工具类
* jie.wu
*/
public class AsymmetricEncryptionUtil {
public static void main(String [] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
//算法名称
String algorithm="RSA";
//私钥长度
int keySize=1024;
//待加密字符串
String str="123456789abc";
//编码格式
String charset="utf8";
//base64 格式的RSA 1024 私钥
String privateKeyBase64="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALfXBP15PeOBS0h20hXZtIyeKiWx9py+VWagxfY2QvWH/+wu8xMpt0WFNWG6nS3ju9u2cViRQUYjRD5kz8hpRy8NdVoV/kbkZeK3LUqZs5/cb378uQTO3LWfOQJFBMz6ll2CXWEjEHGdxzj6iRjFYoC4VS+DDTGO+6iHmYSpP3/1AgMBAAECgYB94VqGYZ1yCZdOACZsVczeOHLtqsUNoPqDMnU62P7SdxRTWfaRWZAnp0XdLFXyFS0ODgfguF10tDNHceog9Y2KS3fHJK3JIur1Y55BqKzLlQlrAWpziaigEw+xJqiO+U67gomlCLTS6kYhFvPGXip3wOctvEh8yG1RX3exTmiVwQJBAPlWm6Aok86vHsBS8Znev1VV9nsSexrJXXkkdHv2ux2JSwQi/WNwWloolUtHFCGcyVmhNEmB7sSbR7/hmaKhiNECQQC8wGySaQIessawFnN/i+xmdoO0OeLCaR9MEce3B5dfRlTq37cfCbGCGnhSi5iRzx4/PHJGNoLPP2xFTVZ5VY3lAkA2rsTgwiVwbb2bxlUQPubNa1XsNehjvofOeq1FRp5Q4vxdwuK5fTmDjmT3pnYGzSDnlFAoUuOvoLKCpZKRNUYRAkALj4WW2hOlKbH9qwJb94f9JpkeesUmvyWJlTU0QqTE0xv0XstqfT+ABnsEI0Su+Y6StPMS1dfhNbM982Sufcz5AkB8OC1vMSQ0oYKxgS3nvNyNlTEjcveJALQAgU7vpSiA0/5LdwUFb7gCKQDL6pq8ySbZ4NV/U5xDVoBzsa5AIEVK";
//base64 格式的 RSA 1024 公钥
String publicKeyBase64="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC31wT9eT3jgUtIdtIV2bSMniolsfacvlVmoMX2NkL1h//sLvMTKbdFhTVhup0t47vbtnFYkUFGI0Q+ZM/IaUcvDXVaFf5G5GXity1KmbOf3G9+/LkEzty1nzkCRQTM+pZdgl1hIxBxncc4+okYxWKAuFUvgw0xjvuoh5mEqT9/9QIDAQAB";
Map<Class,Object> keyPairMap=initKeyPair(algorithm,keySize);
PublicKey publicKey=(PublicKey)keyPairMap.get(PublicKey.class);
PrivateKey privateKey=(PrivateKey) keyPairMap.get(PrivateKey.class);
//加密和解密过程
try {
System.out.println("待加密字符串:str="+str);
//将加密结果转化为Base64编码
String result= new String(Base64.encodeBase64(AsymmetricEncryptionUtil.encrypt(publicKey,algorithm,str.getBytes(charset))),charset);
//加密后得Base64字符串
System.out.println("加密后的字节数组转化为 Base64展示="+result);
//将加密的Base64字符串解密-将解密字节数组转Base64字符串
String ostr= new String(AsymmetricEncryptionUtil.decipher(privateKey,algorithm,Base64.decodeBase64(result)),charset);
System.out.println("原字符串="+ostr);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
//字符串恢复为公私钥对象过程
//私钥恢复为 PrivateKey
PrivateKey priKey=AsymmetricEncryptionUtil.restorePrivateKey(privateKeyBase64,algorithm,charset);
//公钥恢复为 PublicKey
PublicKey pubKey=AsymmetricEncryptionUtil.restorePublicKey(publicKeyBase64,algorithm,charset);
}
/**
* 将 字符串 用指定加密算法 解密
* @param privateKey 私钥
* @param algorithm 算发,如 RSA
* @param strBytes 待解密字节数组
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws UnsupportedEncodingException
*/
public static byte[] decipher(PrivateKey privateKey,String algorithm, byte[] strBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher=Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE,privateKey);
return cipher.doFinal(strBytes);
}
/**
* 将 字符串 用指定加密算法 加密
* @param publicKey 公钥
* @param algorithm 算法,如 RSA
* @param strBytes 待加密字节数组
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] encrypt(PublicKey publicKey,String algorithm,byte[] strBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
//获取 cipher 对象,指定加密算法 比如 RSA
Cipher cipher = Cipher.getInstance(algorithm);
//初始化 cipher 对象,指定为加密模式,指定公钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(strBytes);
}
/**
* 生成 非对称加密算法 公私钥对的方法-返回默认秘钥格式
* @param algorithm 加密算法
* @param keySize 私钥长度-实际会生成一个近似值
* <li>{@code DiffieHellman} (1024)</li>
* <li>{@code DSA} (1024)</li>
* <li>{@code RSA} (1024, 2048)</li>
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<Class,Object> initKeyPair(String algorithm,int keySize) throws NoSuchAlgorithmException {
//指定算法 RSA、DiffieHellman、DSA
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance(algorithm);
//指定私钥的长度——实际生成的也是近似值
keyPairGenerator.initialize(keySize);
//生成公私钥对
KeyPair kPair=keyPairGenerator.generateKeyPair();
Map<Class,Object> keyPairMap=new HashMap<Class,Object>();
keyPairMap.put(PrivateKey.class,kPair.getPrivate());
keyPairMap.put(PublicKey.class,kPair.getPublic());
return keyPairMap;
}
/**
* 生成 非对称加密算法 公私钥对的方法-返回字符Base64 字符串格式
* @param algorithm 加密算法
* @param keySize 私钥长度-实际会生成一个近似值
* @param charset 字符编码格式,如utf8
* <li>{@code DiffieHellman} (1024)</li>
* <li>{@code DSA} (1024)</li>
* <li>{@code RSA} (1024, 2048)</li>
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<Class,Object> initKeyPairBase64Str(String algorithm,int keySize,String charset) throws NoSuchAlgorithmException, UnsupportedEncodingException {
Map<Class,Object> keyPairMap=initKeyPair(algorithm,keySize);
PrivateKey privateKey=(PrivateKey)keyPairMap.get(PrivateKey.class);
PublicKey publicKey=(PublicKey)keyPairMap.get(PublicKey.class);
//以 Base64 格式输出 私钥,指定字符格式 如 utf8、gbk
String privateKeyStr= new String(Base64.encodeBase64(privateKey.getEncoded()),charset);
//以 Base64 格式输出 公钥,指定字符格式 如 utf8、gbk
String publicKeyStr=new String(Base64.encodeBase64(publicKey.getEncoded()),charset);
System.out.println(privateKey.getEncoded().length);
System.out.println(publicKey.getEncoded().length);
//System.out.println("私钥:"+"algorithm:"+privateKey.getAlgorithm()+";format:"+privateKey.getFormat()+";私钥base64:"+privateKeyStr);
//System.out.println("公钥:"+"algorithm:"+publicKey.getAlgorithm()+";format:"+publicKey.getFormat()+";公钥base64:"+publicKeyStr);
keyPairMap.put(PrivateKey.class,privateKeyStr);
keyPairMap.put(PublicKey.class,publicKeyStr);
return keyPairMap;
}
/**
* 由Base64字符编码恢复 公钥
* @param pubKeyBase64Str 公钥 Base64 编码 字符串
* @param algorithm 算法名称,如 RSA\DSA\DiffieHellman
* @param charset 字符编码格式,如 utf8、gbk
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey restorePublicKey(String pubKeyBase64Str,String algorithm,String charset) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
//将Base64 字符串转化为字节数组
byte[] keyBytes=Base64.decodeBase64(pubKeyBase64Str.getBytes(charset));
//公钥标准
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
//指定算法 比如 RSA
KeyFactory factory = KeyFactory.getInstance(algorithm);
//获取公钥
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
return publicKey;
}
/**
* 由Base64字符编码恢复 私钥
* @param privateBase64Str 私钥 Base64 编码字符串
* @param algorithm 算法名称,如 RSA\DSA\DiffieHellman
* @param charset 字符编码格式,如 utf8、gbk
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey restorePrivateKey(String privateBase64Str,String algorithm,String charset) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
//将Base64 字符串转化为字节数组
byte[] keyBytes=Base64.decodeBase64(privateBase64Str.getBytes(charset));
//私钥标准
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
//指定算法,比如 RSA
KeyFactory factory = KeyFactory.getInstance(algorithm);
//获取私钥
PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
}
}
CloseResourceUtils 关闭IO资源
import java.io.Closeable;
import java.io.IOException;
public class CloseableUtils {
public CloseableUtils() {
}
public static void close(Closeable... args) {
if (args != null && args.length != 0) {
Closeable[] arr$ = args;
int len$ = args.length;
for(int i$ = 0; i$ < len$; ++i$) {
Closeable arg = arr$[i$];
try {
if (arg != null) {
arg.close();
}
} catch (IOException var6) {
System.out.println("CloseableUtils.close exception:", var6);
}
}
}
}
}
BrowserInfoUtils 浏览器信息
import javax.servlet.http.HttpServletRequest;
public class BrowserInfoUtils {
/**
* 获取来访者的浏览器版本
* @param request
* @return
*/
public static String getRequestBrowserInfo(HttpServletRequest request){
String browserVersion = null;
String header = request.getHeader("user-agent");
if(header == null || header.equals("")){
return "";
}
if(header.indexOf("MSIE")>0){
browserVersion = "IE";
}else if(header.indexOf("Firefox")>0){
browserVersion = "Firefox";
}else if(header.indexOf("Chrome")>0){
browserVersion = "Chrome";
}else if(header.indexOf("Safari")>0){
browserVersion = "Safari";
}else if(header.indexOf("Camino")>0){
browserVersion = "Camino";
}else if(header.indexOf("Konqueror")>0){
browserVersion = "Konqueror";
}
return browserVersion;
}
}
HttpURLConnectionUtils
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @Title:
* @Description:
* @Copyright: Copyright(c)2018
* @Author: jie.wu
* @Date:2018-09-12 18:18
*/
public class HttpURLConnectionUtils {
/**
* POST 方式发起 httpclient 请求
* @param remoteUrl
* @param xmlStr
* @param encoding
* @return
*/
public static String HttpURLConnectionPost(String remoteUrl, String xmlStr, String encoding){
return sendHttpURLConnection(remoteUrl,xmlStr, encoding,"POST");
}
/**
* httpclient 发送基本方法
* 可以发送xml,json,a=1&b=2&c= 等格式的字符串
*
* @param remoteUrl
* @param xmlStr
* @param encoding ytf8\GBK
* @param requestMethod GET\POST
*
* @return
*/
public static String sendHttpURLConnection(String remoteUrl, String xmlStr, String encoding,String requestMethod) {
String strResponse = "";
String strMessage = "";
InputStream inputStream = null;
OutputStream outputStream = null;
BufferedReader reader = null;
OutputStreamWriter writer = null;
System.out.println("requestXml="+xmlStr);
//logger.info("requestXml={}",xmlStr);
URL url;
HttpURLConnection connection;
try {
url = new URL(remoteUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
//connection.setRequestMethod(requestMethod);
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(true);
// 设置超时
String strTimeOut = "6000";
if (strTimeOut != null) {
connection.setConnectTimeout(Integer.parseInt(strTimeOut));
connection.setReadTimeout(Integer.parseInt(strTimeOut));
}
connection.connect();
outputStream = connection.getOutputStream();
writer = new OutputStreamWriter(outputStream, encoding);
writer.write(xmlStr);
writer.flush();
inputStream = connection.getInputStream();
int status = connection.getResponseCode();
if (status == 200) {
reader = new BufferedReader(new InputStreamReader(inputStream, encoding));
while ((strMessage = reader.readLine()) != null) {
strResponse += strMessage;
}
} else {
strResponse = "error http's status=" + status;
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (reader != null) {
reader.close();
}
if (outputStream != null) {
outputStream.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseXml="+strResponse);
//logger.info("responseXml={}",strResponse);
return strResponse;
}
}
IPAddrUtils 获取ip地址
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import net.sf.json.JSONObject;
public class IPAddrUtils {
/**
* 获取 IP 信息
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
} catch (UnknownHostException e) {
System.out.println("出现异常:"+e.toString());
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length() = 15
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
if("0:0:0:0:0:0:0:1".equals(ipAddress)){
ipAddress="127.0.0.1";
}
return ipAddress;
}
//访问这个地址获取 ip 所属到地区信息
private final static String remoteUrl="http://ip.taobao.com/service/getIpInfo.php?ip=";
private final static String encoding="utf-8";
/**
* 根据 ip 查询地址信息
* @param ip
* @return
*/
public static JSONObject getAreaInfoJsonObjectByIp(String ip){
ip="223.223.193.194";
String xmlStr="";
String result=HttpURLConnectionUtils.HttpURLConnectionPost(remoteUrl+ip, xmlStr, encoding);
if(StringUtils.isNotBlank(result)){
JSONObject json=JSONObject.fromObject(result);
int code=(int)json.get("code");
if(0==code){
JSONObject innerJson=(JSONObject)json.get("data");
System.out.println("ip对应的地区为:"+(String)innerJson.get("country")+innerJson.get("region")+innerJson.getString("city"));
}
return json;
}else{
return null;
}
}
/**
* 根据ip 获取组装好的地址
* @param ip
* @return
*/
public static String getAreaInfoStringByIp(String ip){
JSONObject json=getAreaInfoJsonObjectByIp(ip);
if(json!=null){
int code=(Integer)json.get("code");
if(0==code){
JSONObject innerJson=(JSONObject)json.get("data");
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(innerJson.get("country")).append(innerJson.get("region")).append(innerJson.getString("city"));
return stringBuilder.toString();
}
}else{
return "未知区域";
}
return "未知区域";
}
}
SystemInfoUtils 操作系统信息
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
public class SystemInfoUtils {
private final static Pattern pattern = Pattern.compile(";\\s?[^;\\s]*?(\\s?\\S*?)\\s?(Build)?/");
/**
* 获取系统版本信息
* @param request
* @return
*/
public static String getRequestSystemInfo(HttpServletRequest request){
String systenInfo = null;
String userAgent = request.getHeader("USER-AGENT");
if(userAgent == null || userAgent.equals("")){
return "";
}
System.out.println("userAgent="+userAgent);
boolean isMobile= checkFromMobile(userAgent.toLowerCase());
if(isMobile) {
if(userAgent.indexOf("iPhone") != -1){
return "iPhone";
}
if(userAgent.indexOf("iPad") != -1){
return "iPad";
}
if(userAgent.indexOf("NOKIA") != -1 || userAgent.indexOf("Nokia")!=-1){
return "NOKIA";
}
if(userAgent.indexOf("Windows Phone") != -1){
return "Windows Phone";
}
if(userAgent.indexOf("Nexus") != -1){
return "Nexus";
}
Matcher matcher = pattern.matcher(userAgent);
if (matcher.find()) {
systenInfo = matcher.group(1).trim();
}
}else{
//得到用户的操作系统 https://blog.csdn.net/flyingpig2016/article/details/53282895
if (userAgent.indexOf("NT 6.0") > 0){
systenInfo = "Windows Vista/Server 2008";
} else if (userAgent.indexOf("NT 5.1") > 0){
systenInfo = "Windows XP";
} else if (userAgent.indexOf("NT 6.0") > 0){
systenInfo = "Windows Vista";
} else if (userAgent.indexOf("NT 6.1") > 0){
systenInfo = "Windows 7";
}else if (userAgent.indexOf("NT 6.2") > 0){
systenInfo = "Windows 8";
}else if (userAgent.indexOf("NT 6.3") > 0){
systenInfo = "Windows 9";
} else if (userAgent.indexOf("NT6.4") > 0||userAgent.indexOf("10.0") > 0){
systenInfo = "Windows 10";
}else if (userAgent.indexOf("NT 5") > 0){
systenInfo = "Windows 2000";
} else if (userAgent.indexOf("Mac") > 0){
systenInfo = "Mac";
} else if (userAgent.indexOf("Unix") > 0){
systenInfo = "UNIX";
} else if (userAgent.indexOf("Linux") > 0){
systenInfo = "Linux";
} else if (userAgent.indexOf("SunOS") > 0){
systenInfo = "SunOS";
}else{
systenInfo = "其他";
}
}
return systenInfo;
}
private static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
+"|windows (phone|ce)|blackberry"
+"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
+"|laystation portable)|nokia|fennec|htc[-_]"
+"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
private static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
+"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
private static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
private static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
/**
* 如果是手机端则返回 true
* @param userAgent
* @return
*/
private static boolean checkFromMobile(String userAgent){
if(null == userAgent){
userAgent = "";
}
Matcher matcherPhone = phonePat.matcher(userAgent);
Matcher matcherTable = tablePat.matcher(userAgent);
if(matcherPhone.find() || matcherTable.find()){
return true;
} else {
return false;
}
}
}