根據ip獲取對應地區

注意:此方法引用淘寶網提供的接口。

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 javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
 
/**
 * IP工具類
 * @author Fanpf
 *
 */
public class IpUtil
{
     
    /**
     * 獲取ip對應的區域 
     * 返回結果:中國 華東 南昌市
     * 使用淘寶網所提供接口
     * @param IP
     * @return
     */
    public static String GetAddressByIp(String IP){
        String resout = "";
        try{
         String str = getJsonContent("http://ip.taobao.com/service/getIpInfo.php?ip="+IP);
         JSONObject obj = JSONObject.fromObject(str);
         JSONObject obj2 =  (JSONObject) obj.get("data");
         Object code = obj.get("code");
         if(String.valueOf(code).equals("0")){
             resout =  obj2.get("country")+" " +obj2.get("area")+" " +obj2.get("city");
         }else{
             resout =  "未知IP";
         }
        }catch(Exception e){
            e.printStackTrace();
             resout = "獲取IP地址異常";
        }
        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;
    }
    
    public static void main(String[] args) {
    System.out.println(GetAddressByIp("218.64.55.225"));
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章