获取外网ip并通过ip获取城市信息

http://pv.sohu.com/cityjson?ie=utf-8获取外网ip接口

该方法调用返回的外网ip即可获取国家

package com.dy.util;

import com.jfinal.json.FastJson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class IpUtils {

    //通过ip获取国家
    public static String ipToCountry(String ip){
        String sohu="http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
        String read="";
        URL url=null;
        HttpURLConnection urlConnection=null;
        BufferedReader in=null;
        try {
            url=new URL(sohu);
            urlConnection=(HttpURLConnection)url.openConnection();
            in=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
            read=in.readLine();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Map readMap = FastJson.getJson().parse(read, Map.class);
        Map data = FastJson.getJson().parse(readMap.get("data").toString(), Map.class);
        return data.get("country").toString();
    }

    public static void main(String[] args) {
        String s = IpUtils.ipToCountry("125.47.109.86");
        System.out.println(s);
    }
}

你可能感兴趣的:(项目)