根據ip解析相應的地址,呼叫淘寶介面
阿新 • • 發佈:2019-01-10
package org.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.isli.deal.resolution.pojo.AreaInfo;
/**
* 根據ip 解析取到相應的地址
*
* @author
*
*/
public class AddressUtil {
private static final Logger LOGGER = Logger
.getLogger(KafkaConsumerUtil.class);
private static final String ANALYSIS_IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
private static Map<String, AreaInfo> addressMap = Collections
.synchronizedMap(new HashMap<String, AreaInfo>());
/**
* IP轉換成地址
*
* @param ip
* @return
*/
public AreaInfo getAddressByIp(String ip) {
LOGGER.info("===param..." + ip);
AreaInfo area = null;
try {
if (null != ip && !"".equals(ip)) {
// 超過20000條,清快取
if (addressMap.size() > ConstantNumber.TWENTY_THOUSAND) {
addressMap.clear();
}
area = addressMap.get(ip);
if (null == area) {
area = getAddresses(ip, "UTF-8");
if (null != area) {
addressMap.put(ip, area);
}
}
}
} catch (Exception e) {
LOGGER.info("[AddressUtil.getAddressByIp]" + e.getMessage());
}
return area;
}
/**
*
* @param ip
* 請求的引數 格式為:183.16.9.216
* @param encoding
* 伺服器端請求編碼。如GBK,UTF-8等
* @return
* @throws Exception
*/
public AreaInfo getAddresses(String ip, String encodingString)
throws Exception {
AreaInfo areaInfo = null;
try {
// 取得IP所在的國家省市資訊
String returnStr = getResult(ANALYSIS_IP_URL, ip, encodingString);
if (null != returnStr && !"".equals(returnStr)) {
// 處理返回的省市區資訊
LOGGER.info(returnStr);
String[] temp = returnStr.split(",");
if (temp.length > ConstantNumber.NUM_EIGHT) {
areaInfo = new AreaInfo();
String countryId = (temp[2].split(":"))[1].replaceAll("\"",
"");
String country = "";
String province = "";
String city = "";
if ("IANA".equals(countryId)) {
// 表示內網
country = "中國";
province = "廣東省";
city = "深圳市";
} else {
// 國家1
country = (temp[1].replaceAll("\\:\\{", "")
.split(":"))[1].replaceAll("\"", "");
country = decodeUnicode(country);
// 省份5
province = (temp[ConstantNumber.NUM_FIVE].split(":"))[1]
.replaceAll("\"", "");
province = decodeUnicode(province);
// 城市7
city = (temp[ConstantNumber.NUM_SEVEN].split(":"))[1]
.replaceAll("\"", "");
city = decodeUnicode(city);
}
LOGGER.info("country=" + country + ",province=" + province
+ ",city=" + city);
areaInfo.setCountry(country);
areaInfo.setProvince(province);
areaInfo.setCity(city);
}
}
} catch (Exception e) {
LOGGER.info("[AddressUtil.getAddresses]" + e);
e.printStackTrace();
}
return areaInfo;
}
/**
* @param urlStr
* 請求的地址
* @param ip
* 請求的引數 格式為:183.16.9.216
* @param encoding
* 伺服器端請求編碼。如GBK,UTF-8等
* @return
*/
private String getResult(String urlStr, String ip, String encoding) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = urlStr + "?ip=" + ip;
URL realUrl = new URL(urlNameString);
// 開啟和URL之間的連線
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連線
connection.connect();
// 獲取所有響應頭欄位
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭欄位
for (String key : map.keySet()) {
LOGGER.info(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
LOGGER.info("傳送GET請求出現異常!" + e);
e.printStackTrace();
} finally {
// 使用finally塊來關閉輸入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
LOGGER.info("[AddressUtil.getResult]" + result);
return result;
}
/**
* unicode 轉換成 中文
*
* @param theString
* @return
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < ConstantNumber.NUM_FOUR; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << ConstantNumber.NUM_FOUR)
+ aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << ConstantNumber.NUM_FOUR)
+ ConstantNumber.NUM_TEN + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << ConstantNumber.NUM_FOUR)
+ ConstantNumber.NUM_TEN + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"[AddressUtil.decodeUnicode]Malformed encoding");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
// 測試
public static void main(String[] args) {
AddressUtil addressUtils = new AddressUtil();
// 測試ip 183.16.9.216 中國廣東深圳 電信
String ip = "183.16.9.216";
try {
AreaInfo area = addressUtils.getAddressByIp(ip);
if (null != area) {
LOGGER.info(area.getCountry() + "," + area.getProvince() + ","
+ area.getCity());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.isli.deal.resolution.pojo.AreaInfo;
/**
* 根據ip 解析取到相應的地址
*
* @author
*
*/
public class AddressUtil {
private static final Logger LOGGER = Logger
.getLogger(KafkaConsumerUtil.class);
private static final String ANALYSIS_IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
private static Map<String, AreaInfo> addressMap = Collections
.synchronizedMap(new HashMap<String, AreaInfo>());
/**
* IP轉換成地址
*
* @param ip
* @return
*/
public AreaInfo getAddressByIp(String ip) {
LOGGER.info("===param..." + ip);
AreaInfo area = null;
try {
if (null != ip && !"".equals(ip)) {
// 超過20000條,清快取
if (addressMap.size() > ConstantNumber.TWENTY_THOUSAND) {
addressMap.clear();
}
area = addressMap.get(ip);
if (null == area) {
area = getAddresses(ip, "UTF-8");
if (null != area) {
addressMap.put(ip, area);
}
}
}
} catch (Exception e) {
LOGGER.info("[AddressUtil.getAddressByIp]" + e.getMessage());
}
return area;
}
/**
*
* @param ip
* 請求的引數 格式為:183.16.9.216
* @param encoding
* 伺服器端請求編碼。如GBK,UTF-8等
* @return
* @throws Exception
*/
public AreaInfo getAddresses(String ip, String encodingString)
throws Exception {
AreaInfo areaInfo = null;
try {
// 取得IP所在的國家省市資訊
String returnStr = getResult(ANALYSIS_IP_URL, ip, encodingString);
if (null != returnStr && !"".equals(returnStr)) {
// 處理返回的省市區資訊
LOGGER.info(returnStr);
String[] temp = returnStr.split(",");
if (temp.length > ConstantNumber.NUM_EIGHT) {
areaInfo = new AreaInfo();
String countryId = (temp[2].split(":"))[1].replaceAll("\"",
"");
String country = "";
String province = "";
String city = "";
if ("IANA".equals(countryId)) {
// 表示內網
country = "中國";
province = "廣東省";
city = "深圳市";
} else {
// 國家1
country = (temp[1].replaceAll("\\:\\{", "")
.split(":"))[1].replaceAll("\"", "");
country = decodeUnicode(country);
// 省份5
province = (temp[ConstantNumber.NUM_FIVE].split(":"))[1]
.replaceAll("\"", "");
province = decodeUnicode(province);
// 城市7
city = (temp[ConstantNumber.NUM_SEVEN].split(":"))[1]
.replaceAll("\"", "");
city = decodeUnicode(city);
}
LOGGER.info("country=" + country + ",province=" + province
+ ",city=" + city);
areaInfo.setCountry(country);
areaInfo.setProvince(province);
areaInfo.setCity(city);
}
}
} catch (Exception e) {
LOGGER.info("[AddressUtil.getAddresses]" + e);
e.printStackTrace();
}
return areaInfo;
}
/**
* @param urlStr
* 請求的地址
* @param ip
* 請求的引數 格式為:183.16.9.216
* @param encoding
* 伺服器端請求編碼。如GBK,UTF-8等
* @return
*/
private String getResult(String urlStr, String ip, String encoding) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = urlStr + "?ip=" + ip;
URL realUrl = new URL(urlNameString);
// 開啟和URL之間的連線
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連線
connection.connect();
// 獲取所有響應頭欄位
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭欄位
for (String key : map.keySet()) {
LOGGER.info(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
LOGGER.info("傳送GET請求出現異常!" + e);
e.printStackTrace();
} finally {
// 使用finally塊來關閉輸入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
LOGGER.info("[AddressUtil.getResult]" + result);
return result;
}
/**
* unicode 轉換成 中文
*
* @param theString
* @return
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < ConstantNumber.NUM_FOUR; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << ConstantNumber.NUM_FOUR)
+ aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << ConstantNumber.NUM_FOUR)
+ ConstantNumber.NUM_TEN + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << ConstantNumber.NUM_FOUR)
+ ConstantNumber.NUM_TEN + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"[AddressUtil.decodeUnicode]Malformed encoding");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
// 測試
public static void main(String[] args) {
AddressUtil addressUtils = new AddressUtil();
// 測試ip 183.16.9.216 中國廣東深圳 電信
String ip = "183.16.9.216";
try {
AreaInfo area = addressUtils.getAddressByIp(ip);
if (null != area) {
LOGGER.info(area.getCountry() + "," + area.getProvince() + ","
+ area.getCity());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}