获取客户IP并查询IP的地理位置(使用淘宝IP地址库)
2014-03-12 14:30
661 查看
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class IpUtil { public static String getIpAddr(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(); } if (ip.equals("0:0:0:0:0:0:0:1")) { ip = "本地"; } if (ip.split(",").length > 1) { ip = ip.split(",")[0]; } return getIpInfo(ip); } public static String getIpInfo(String ip) { String info = ""; try { URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip); HttpURLConnection htpcon = (HttpURLConnection) url.openConnection(); htpcon.setRequestMethod("GET"); htpcon.setDoOutput(true); htpcon.setDoInput(true); htpcon.setUseCaches(false); InputStream in = htpcon.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); StringBuffer temp = new StringBuffer(); String line = bufferedReader.readLine(); while (line != null) { temp.append(line).append("\r\n"); line = bufferedReader.readLine(); } bufferedReader.close(); JSONObject obj = (JSONObject) JSON.parse(temp.toString()); if (obj.getIntValue("code") == 0) { JSONObject data = obj.getJSONObject("data"); info += data.getString("country") + " "; info += data.getString("region") + " "; info += data.getString("city") + " "; info += data.getString("isp"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return info; } }
相关文章推荐
- 使用淘宝IP库获取用户ip地理位置
- 利用【淘宝IP地址库】根据客户ip获取客户地理信息
- 使用PHP+淘宝IP地址库接口获得IP所属地理位置
- 使用淘宝IP库获取用户ip地理位置
- ASP.NET2.0中根据IP来获取客户的地理位置
- 获取用户真实 IP , 淘宝IP接口获得ip地理位置
- PHP获取用户真实 IP , 淘宝IP接口获得ip地理位置
- php利用新浪接口查询ip获取地理位置示例
- python通过淘宝IP地址库获取IP位置
- PHP获取用户真实 IP , 淘宝IP接口获得ip地理位置
- 通过淘宝IP地址库获取IP位置
- PHP获取用户真实 IP , 淘宝IP接口获得ip地理位置
- PHP获取用户真实 IP , 淘宝IP接口获得ip地理位置
- 通过淘宝IP地址库获取IP位置
- 通过淘宝IP地址库获取IP位置
- ahjesus可供C#使用的ip地理位置查询插件
- python使用在线API查询IP对应的地理位置信息实例
- 使用Retrofit和淘宝IP地址库查询IP
- PHP获取用户真实 IP , 淘宝IP接口获得ip地理位置