1. 程式人生 > >java web獲取ip,並獲取ip所在的地址

java web獲取ip,並獲取ip所在的地址

獲取IP地址:

private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }

獲取地址:

private String getAdd(HttpServletRequest request) {
        //淘寶IP地址庫:http://ip.taobao.com/instructions.php
String add = null; String ip = getIp(request); try { //URL U = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=114.111.166.72"); URL U = new URL("http://ip.taobao.com/service/getIpInfo.php?ip="+ip); URLConnection connection = U.openConnection(); connection.
connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine())!= null){ result += line; } in.close(); JSONObject jsonObject = JSONObject.fromObject(result); Map<String, Object> map = (Map) jsonObject; String code = String.valueOf(map.get("code"));//0:成功,1:失敗。 if("1".equals(code)){//失敗 String data = String.valueOf(map.get("data"));//錯誤資訊 }else if("0".equals(code)){//成功 Map<String, Object> data = (Map<String, Object>) map.get("data"); String country = String.valueOf(data.get("country"));//國家 String area = String.valueOf(data.get("area"));// String city = String.valueOf(data.get("city"));//省(自治區或直轄市) String region = String.valueOf(data.get("region"));//市(縣) add = country+"-"+city+"-"+region; } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }