当前位置: 移动技术网 > IT编程>开发语言>Java > java实现根据ip地址获取地理位置

java实现根据ip地址获取地理位置

2019年07月22日  | 移动技术网IT编程  | 我要评论

最近项目某个功能需要根据ip地址从第三方接口获取详细的地理位置,从网上找了很多例子,主要接口有新浪的,淘宝的,腾讯的。试了淘宝的,如果是数量级小的还可以,如果数量级达到上十万级就速度慢了,会导致系统崩溃。下面例子是新浪的,例子不是适合每个项目,需要改一下.

/**
 ipsearchurl=http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=(这是新浪的接口地址)
  在项目中新浪的接口地址没有直接写死,而是去读属性文件。
*/
  public static string getipinfobysina(string ip){
   // 读取属性文件(属性文件key-value和格式)
    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);//这个是从属性文件中获取url,即新浪接口地址
    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;
  }

读新浪的接口地址很快,我本人测试到了九万条左右,十分钟。淘宝的话一个多小时,五万多条。还有一个小技巧,就是把读到的ip存到map中,然后下次读的话就直接从map取出,这样快很多。这个会衍生出很多问题,当日志文件达到百万级,千万级,怎么解决。类似淘宝这样的,一秒多少订单,每个订单ip不一样。我不知道怎么解决。有大神知道回我一下。
下面是用淘宝的。

 
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;

/**
 * 根据ip地址获取详细的地域信息 
* @author lwl
* @datejan 26, 2016
 */
public class addressutils {
 
/** 
 * 
 * @param content 
 *      请求的参数 格式为:name=xxx&pwd=xxx 
 * @param encoding 
 *      服务器端请求编码。如gbk,utf-8等 
 * @return 
 * @throws unsupportedencodingexception 
 */ 
 public string getaddresses(string content, string encodingstring) 
  throws unsupportedencodingexception { 
 // 这里调用pconline的接口 
 string urlstr = "http://ip.taobao.com/service/getipinfo.php"; 
 // 从http://whois.pconline.com.cn取得ip所在的省市区信息 
 string returnstr = this.getresult(urlstr, content, encodingstring); 
 if (returnstr != null) { 
  // 处理返回的省市区信息 
  system.out.println(returnstr); 
  string[] temp = returnstr.split(","); 
  if(temp.length<3){ 
  return "0";//无效ip,局域网测试 
  } 
  string region = (temp[5].split(":"))[1].replaceall("\"", ""); 
  region = decodeunicode(region);// 省份 
  
      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);// 国家 
          break; 
          case 3: 
            area = (temp[i].split(":"))[1].replaceall("\"", ""); 
            area = decodeunicode(area);// 地区  
          break; 
          case 5: 
            region = (temp[i].split(":"))[1].replaceall("\"", ""); 
            region = decodeunicode(region);// 省份  
          break;  
          case 7: 
            city = (temp[i].split(":"))[1].replaceall("\"", ""); 
            city = decodeunicode(city);// 市区 
          break;  
          case 9: 
              county = (temp[i].split(":"))[1].replaceall("\"", ""); 
              county = decodeunicode(county);// 地区  
          break; 
          case 11: 
            isp = (temp[i].split(":"))[1].replaceall("\"", ""); 
            isp = decodeunicode(isp); // isp公司 
          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 
 *      请求的地址 
 * @param content 
 *      请求的参数 格式为:name=xxx&pwd=xxx 
 * @param encoding 
 *      服务器端请求编码。如gbk,utf-8等 
 * @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();// 新建连接实例 
  connection.setconnecttimeout(2000);// 设置连接超时时间,单位毫秒 
  connection.setreadtimeout(33000);// 设置读取数据超时时间,单位毫秒 
  connection.setdooutput(true);// 是否打开输出流 true|false 
  connection.setdoinput(true);// 是否打开输入流true|false 
  connection.setrequestmethod("post");// 提交方法post|get 
  connection.setusecaches(false);// 是否缓存true|false 
  connection.connect();// 打开连接端口 
  dataoutputstream out = new dataoutputstream(connection.getoutputstream());// 打开输出流往对端服务器写数据 
  out.writebytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx 
  out.flush();// 刷新 
  out.close();// 关闭输出流 
  bufferedreader reader = new bufferedreader(new inputstreamreader( 
   connection.getinputstream(), encoding));// 往对端写完数据对端服务器返回数据 
  // ,以bufferedreader流来读取 
  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();// 关闭连接 
  } 
 } 
 return null; 
 } 
 /** 
 * unicode 转换成 中文 
 * 
 * @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(); 
 } 
 // 测试 
 public static void main(string[] args) { 
 addressutils addressutils = new addressutils(); 
 // 测试ip 219.136.134.157 中国=华南=广东省=广州市=越秀区=电信 
 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); 
 // 输出结果为:广东省,广州市,越秀区 
 } 
 
 
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网