Java implementation obtains geographic location based on IP address _java

Source: Internet
Author: User
Tags get ip stringbuffer

Recent project a feature needs to be based on IP address from Third-party interface to obtain a detailed geographical location, from the Internet to find a lot of examples, the main interface with Sina, Taobao, Tencent. Try Taobao, if it is a small order of magnitude can also, if the order of magnitude to reach the 100,000 level on the slow speed, will lead to system crashes. The following example is Sina, the example is not suitable for each project, need to change.

/** ipsearchurl=http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip= (This is Sina's interface address)
In the project Sina's interface address is not directly written dead, but to read the property file. */public static string Getipinfobysina (String IP) {//Read Property file (property file Key-value and format) final String prop_ipsearchurl= IP
    Searchurl ";
    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 the URL in the subordinate file, that is, the Sina interface address if (Strin Gutils.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's interface address quickly, I personally tested to 90,000 or so, 10 minutes. Taobao words one hours, more than 50,000. Another trick is to store the IP you read in the map, and then take it out of the map the next time you read it, so much faster. This will spawn a lot of problems, the log file to reach millions, tens, how to solve. such as Taobao, a second number of orders, each order IP is not the same. I don't know how to solve it. A great God knows to return to me.
The following is the use of 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;       /** * Obtain detailed geographic information based on IP address * @author LWL * @dateJan, 2016/public class Addressutils {/** * * @param content * The requested parameter format is: NAME=XXX&AMP;PWD=XXX * @param encoding * server-side request encoding. such as Gbk,utf-8 * @return * @throws unsupportedencodingexception/public string getaddresses (string content, string encodingstring) throws Unsupportedencodingexception {//Here calls the Pconline interface String urlstr = "Http://ip.taobao.com/serv 
 Ice/getipinfo.php "; 
 From http://whois.pconline.com.cn get IP in the provinces and cities of information String returnstr = This.getresult (urlstr, Content, encodingstring); 
  if (returnstr!= null) {//processing the returned province 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);//province 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);//State break; 
            Case 3:area = (Temp[i].split (":")) [1].replaceall ("\" "," "); 
          Zone = Decodeunicode (area);//region break; 
            Case 5:region = (Temp[i].split (":")) [1].replaceall ("\" "," ");  
          Region = Decodeunicode (region);//Province break; 
            Case 7:city = (Temp[i].split (":")) [1].replaceall ("\" "," ");  
          City = Decodeunicode (urban); Case 9:county = (Temp[i].split (":")) [1].ReplaceAll ("\" "," "); 
          County = Decodeunicode (county);//region break; 
            Case 11:isp = (Temp[i].split (":")) [1].replaceall ("\" "," "); ISP = Decodeunicode (ISP); 
        The ISP company break; 
  } System.out.println (Country+area+region+city+county+isp); 
 Return to New StringBuffer (country). Append (area). Append (Region). Append (city). Append (county). append (ISP). toString (); 
 return null; 
 /** * @param URLSTR * Requested address * @param content * Requested parameter format is: NAME=XXX&AMP;PWD=XXX * @param encoding * Server-side request encoding. such as 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 ()//New Connection Instance Connection.setconnecttimeout (2000);//Set connection timeout, per millisecond Connection.setreadtimeout (33000)//sets the read Data timeout, unit milliseconds CONNECTION.SETDOOUTPUT (true);//whether to open the output stream True|false Connection.setdoinput (TRUE);//Open input stream true|false connection.setrequestmethod ("POST") ;//Submit Method post| Get Connection.setusecaches (FALSE)//whether to cache True|false connection.connect ();//Open connection port dataoutputstream out = new Da Taoutputstream (Connection.getoutputstream ())//open output stream to the end server write data out.writebytes (content);//write data, that is, submit your form name=xxx &pwd=xxx Out.flush ()//Refresh Out.close ();//close output stream BufferedReader reader = new BufferedReader (New Inputstreamrea Der (Connection.getinputstream (), encoding))//To the end of the data to the end of the server return data//, BufferedReader stream to read StringBuffer buffer = n 
  EW 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 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 ': CAs 
    E ' 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) + + ACh 
    AR-' a '; 
   Break Case ' A ': Case ' B ': Case ' C ': Case ' D ': Case ' E ': Case ' F ': value = (value << 4) + + ACh 
    AR-' 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 of Guangdong = 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 is: Guangdong Province, Guangzhou, Yuexiu District}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.