Java联网查询IP地址归属,使用腾讯ip分享计划接口以及淘宝API接口

关于Java联网查询IP地址归属问题,在网上基本找到以下两种解决方案。

第一种是调用“腾讯ip分享计划”提供的接口,代码如下。

    public String getAddressByIP()  
    {   
        try  
        {  
            String strIP = "0.0.0.0";  
            URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP);   
            URLConnection conn = url.openConnection();   
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));   
            String line = null;   
            StringBuffer result = new StringBuffer();   
            while((line = reader.readLine()) != null)  
            {   
                result.append(line);   
            }   
            reader.close();   
            strIP = result.substring(result.indexOf( "该IP所在地为:" ));  
            strIP = strIP.substring(strIP.indexOf( ":") + 1);  
            String province = strIP.substring(6, strIP.indexOf("省"));  
            String city = strIP.substring(strIP.indexOf("省") + 1, strIP.indexOf("市"));  
            ... ...  
            ... ...  
        }  
        catch( IOException e)  
        {   
            return "读取失败";   
        }  

 }   

但是其放在我的系统中运行出错,在获取StrIp的地方出现异常。很遗憾,没有找到原因。

第二种是调用淘宝API联网查询,代码如下。
package getAddressByIp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;
 
public class GetAddressByIp
{  
    /**
     * 
     * @param IP
     * @return
     */
    public static String GetAddressByIp(String IP){
        String resout = "";
        try{
         String str = getJsonContent("http://ip.taobao.com/service/getIpInfo.php?ip="+IP);
         System.out.println(str);
          
         JSONObject obj = JSONObject.fromObject(str);
         JSONObject obj2 =  (JSONObject) obj.get("data");
         String code = (String) obj.get("code");
         if(code.equals("0")){      
             resout =  obj2.get("country")+"--" +obj2.get("area")+"--" +obj2.get("city")+"--" +obj2.get("isp");
         }else{
             resout =  "IP地址有误";
         }
        }catch(Exception e){        
            e.printStackTrace();
             resout = "获取IP地址异常:"+e.getMessage();
        }
        return resout;     
    }
    
    public static String getJsonContent(String urlStr)
    {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return "";
    }
    
    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}
放在我的系统中运行同样出错,异常内容为:异常内容为:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException

网上百度了一下原因,原来是要用commons-lang-2.4.jar这个包,我的系统中是commons-lang3-3.4.jar,而lang3与lang目录有改变,所以会有错误。由于系统要使用lang3版本,因此此种方法也无法使用。

后来没办法,我还是用的淘宝的API来联网查询,只不过对于获取到的信息用GSON进行解析的,代码如下:

public static String getAddressByIP(String strIP)
    { 
      try
      {
        URL url = new URL( "http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP); 
        URLConnection conn = url.openConnection(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK")); 
        String line = null; 
        StringBuffer result = new StringBuffer(); 
        while((line = reader.readLine()) != null)
        { 
          result.append(line); 
        } 
        reader.close(); 
        if(result.indexOf("0")==8){
        	String json_date = result.substring(17, result.length()-1);
    		Gson gson = new Gson();
    		IPAddress address = gson.fromJson(json_date,IPAddress.class);
    		if(address.getRegion().equals("")){
    			return null;
    		}
            return address.getRegion();
        }else{
        	return null;
        }
      }
      catch( IOException e)
      { 
        return "读取失败"; 
      }
    }
public class IPAddress {

    String country;
    String country_id;
    String area;
    String area_id;
    String region;
    String region_id;
    String city;
    String city_id;
    String county;
    String county_id;
    String isp;
    String isp_id;
    String ip;
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getCountry_id() {
        return country_id;
    }
    public void setCountry_id(String countryId) {
        country_id = countryId;
    }
    public String getArea() {
        return area;
    }
    public void setArea(String area) {
        this.area = area;
    }
    public String getArea_id() {
        return area_id;
    }
    public void setArea_id(String areaId) {
        area_id = areaId;
    }
    public String getRegion() {
        return region;
    }
    public void setRegion(String region) {
        this.region = region;
    }
    public String getRegion_id() {
        return region_id;
    }
    public void setRegion_id(String regionId) {
        region_id = regionId;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCity_id() {
        return city_id;
    }
    public void setCity_id(String cityId) {
        city_id = cityId;
    }
    public String getCounty() {
        return county;
    }
    public void setCounty(String county) {
        this.county = county;
    }
    public String getCounty_id() {
        return county_id;
    }
    public void setCounty_id(String countyId) {
        county_id = countyId;
    }
    public String getIsp() {
        return isp;
    }
    public void setIsp(String isp) {
        this.isp = isp;
    }
    public String getIsp_id() {
        return isp_id;
    }
    public void setIsp_id(String ispId) {
        isp_id = ispId;
    }
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
}

解析出来的代码如下:

{"code":0,"data":{"country":"\u4e2d\u56fd","country_id":"CN","area":"\u534e\u5317","area_id":"100000","region":"\u5317\u4eac\u5e02","region_id":"110000","city":"\u5317\u4eac\u5e02","city_id":"110100","county":"","county_id":"-1","isp":"\u9e4f\u535a\u58eb","isp_id":"1000143","ip":"XXX.XXX.XXX.XXX"}}

IPAddress类是我根据解析到的数据自己设定的。至此,终于成功。写贴纪念一下。




你可能感兴趣的:(Java联网查询IP地址归属,使用腾讯ip分享计划接口以及淘宝API接口)