The java implementation gets the geographical location based on the ip address
- 2020-05-07 19:37:17
- OfStack
Recently, a function of the project needs to obtain a detailed geographical location from the third party interface according to the ip address. I have found many examples from the Internet, and the main interfaces are sina, taobao and teng xun. Tried taobao, if the order of magnitude is small can also be, if the order of magnitude reached 100,000 level on the speed is slow, will cause the system crash. The following example is from sina. It is not suitable for every project and needs to be changed by 1.
/**
ipSearchUrl=http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip= (this is the interface address of sina)
In the project sina interface address is not directly written dead, but to read the property file.
*/
public static String getIpInfoBySina(String ip){
// Read properties file ( Properties file key-value And format )
final String PROP_IPSEARCHURL="ipSearchUrl";
final String RET_SUCCESS="1";
final String RET="ret";
final String PROVINCE="province";
final String CITY="city";
final String DISTRICT="district";
final String ISP="isp";
String ipAddress="";
if(StringUtils.isBlank(ip)){
return null;
}
String url = SystemParamPropertyUtils.getSystemParamKeyValue(PROP_IPSEARCHURL);// This is from the properties file url , namely sina interface address
if(StringUtils.isNotBlank(url)){
String path=url+ip;//"http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip="+ip;
HttpClient httpClient = new HttpClient();
Map<String, String> paramMap = new HashMap<String, String>();
String remoteIpInfo="";
try {
remoteIpInfo = HttpClientUtil.request(httpClient, path, paramMap,"sina");
} catch (Exception e) {
e.printStackTrace();
}
if(StringUtils.isNotBlank(remoteIpInfo)){
String _ret=searchValue(remoteIpInfo, RET);
if(RET_SUCCESS.equals(_ret)){
String provinceName=searchValue(remoteIpInfo, PROVINCE);
String cityName=searchValue(remoteIpInfo, CITY);
String district=searchValue(remoteIpInfo, DISTRICT);
String isp=searchValue(remoteIpInfo, ISP);
ipAddress=provinceName+cityName+district+isp;
}
}
}
return ipAddress;
}
private static String searchValue(String remoteIpInfo,String key){
String _value="";
if(StringUtils.isNotBlank(remoteIpInfo)){
_value=StringUtils.substringBetween(remoteIpInfo,"\""+key+"\":", ",");
if(StringUtils.isNotBlank(_value)){
_value=UnicodeUtils.decodeUnicode(_value);
}
}
return _value;
}
Read sina interface address very quickly, I personally tested to about 90,000, 10 minutes. Taobao more than an hour, more than 50,000 pieces. Another tip is to save the ip you read into map, and then take it out of map the next time you read, which is much faster. This can lead to a lot of problems, when the log files reach millions, tens of millions, how to solve them. Similar to taobao, how many orders per second, each order ip is not one. I don't know how to solve it. A great god knows to return me 1.
The following is taobao.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* According to the IP Addresses get detailed geographic information
* @author Lwl
* @dateJan 26, 2016
*/
public class AddressUtils {
/**
*
* @param content
* Parameters of the request Format for: name=xxx&pwd=xxx
* @param encoding
* Server-side request encoding. Such as GBK,UTF-8 Etc.
* @return
* @throws UnsupportedEncodingException
*/
public String getAddresses(String content, String encodingString)
throws UnsupportedEncodingException {
// This call pconline The interface of the
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
// from http://whois.pconline.com.cn achieve IP Information of the province and city where it is located
String returnStr = this.getResult(urlStr, content, encodingString);
if (returnStr != null) {
// Process the returned provincial information
System.out.println(returnStr);
String[] temp = returnStr.split(",");
if(temp.length<3){
return "0";// invalid IP , LAN test
}
String region = (temp[5].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);// provinces
String country = "";
String area = "";
// String region = "";
String city = "";
String county = "";
String isp = "";
for (int i = 0; i < temp.length; i++) {
switch (i) {
case 1:
country = (temp[i].split(":"))[2].replaceAll("\"", "");
country = decodeUnicode(country);// countries
break;
case 3:
area = (temp[i].split(":"))[1].replaceAll("\"", "");
area = decodeUnicode(area);// region
break;
case 5:
region = (temp[i].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);// provinces
break;
case 7:
city = (temp[i].split(":"))[1].replaceAll("\"", "");
city = decodeUnicode(city);// The city
break;
case 9:
county = (temp[i].split(":"))[1].replaceAll("\"", "");
county = decodeUnicode(county);// region
break;
case 11:
isp = (temp[i].split(":"))[1].replaceAll("\"", "");
isp = decodeUnicode(isp); // ISP The company
break;
}
}
System.out.println(country+area+region+city+county+isp);
return new StringBuffer(country).append(area).append(region).append(city).append(county).append(isp).toString();
}
return null;
}
/**
* @param urlStr
* Requested address
* @param content
* Parameters of the request Format for: name=xxx&pwd=xxx
* @param encoding
* Server-side request encoding. Such as GBK,UTF-8 Etc.
* @return
*/
private String getResult(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();// New connection instance
connection.setConnectTimeout(2000);// Set the connection timeout in milliseconds
connection.setReadTimeout(33000);// Set the read timeout in milliseconds
connection.setDoOutput(true);// Whether to open the output stream true|false
connection.setDoInput(true);// Whether to open the input stream true|false
connection.setRequestMethod("POST");// Submission methods POST|GET
connection.setUseCaches(false);// Whether the cache true|false
connection.connect();// Open connection port
DataOutputStream out = new DataOutputStream(connection.getOutputStream());// Turn on the output stream to write data to the opposite server
out.writeBytes(content);// Write the data , Submit your form name=xxx&pwd=xxx
out.flush();// The refresh
out.close();// Close the output stream
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), encoding));// Write the data to the opposite end the server returns the data to the opposite end
// , In order to BufferedReader Flow to read
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();// Close the connection
}
}
return null;
}
/**
* unicode Converted to Chinese
*
* @author fanhui 2007-3-15
* @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 < 4; 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 << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"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();
}
// test
public static void main(String[] args) {
AddressUtils addressUtils = new AddressUtils();
// test ip 219.136.134.157 China = South China = Guangdong province, = guangzhou = Yuexiu district = telecom
String ip = "125.70.11.136";
String address = "";
try {
address = addressUtils.getAddresses("ip="+ip, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(address);
// The output result is: guangdong province , guangzhou , Yuexiu district
}
}