Java联网查询IP地址归属地

基本原理就是发出一个HTTP请求给淘宝查询IP的网址,再解析返回来的JSON.

其中淘宝返回的json如下:

{"code":0,"data":{"country":"\u672a\u5206\u914d\u6216\u8005\u5185\u7f51IP","country_id":"IANA","area":"","area_id":"","region":"","region_id":"","city":"","city_id":"","county":"","county_id":"","isp":"","isp_id":"","ip":"127.0.0.1"}}

其中要引入两个jar包。


package org.max.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class IpAddressUtil {
    public static String getAddressByIp(String ip) throws IOException{
        URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip="+ip);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        String content = IOUtils.toString(httpConn.getInputStream());
        JSONObject js = JSON.parseObject(content);
        JSONObject detail = (JSONObject)js.get("data");
        StringBuilder sb = new StringBuilder();
        sb.append(detail.get("country"));
        sb.append(detail.get("region"));
        sb.append(detail.get("city"));
        sb.append("  ");
        sb.append(detail.get("isp"));
        return sb.toString();
    }
    public static void main(String[] args) throws IOException {
        String ip = "112.112.112.112";
        String result = getAddressByIp(ip);
        System.out.println(ip+" 归属于:"+result);
        String ip1 = "127.0.0.1";
        String result1 = getAddressByIp(ip1);
        System.out.println(ip1+" 归属于:"+result1);
    }
}

运行结果如下:





你可能感兴趣的:(java,json)