Java 根据IP获取地址
用淘宝接口:(源码:java 根据IP地址获取地理位置)
pom.xml:
<!-- https://mvnrepository.com/artifact/net.sourceforge.jregex/jregex -->
<dependency>
<groupId>net.sourceforge.jregex</groupId>
<artifactId>jregex</artifactId>
<version>1.2_01</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
AddressUtils.java:
package com.euphe.util; import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; public class AddressUtils {
/**
*
* @param content
* 请求的参数 格式为:name=xxx&pwd=xxx
* @param encodingString
* 服务器端请求编码。如GBK,UTF-8等
* @return
* @throws UnsupportedEncodingException
*/
public static String getAddresses(String content, String encodingString){
//调用淘宝API
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
String returnStr = getResult(urlStr, content,encodingString);
if(returnStr != null){
System.out.println(returnStr);
return returnStr;
}
return null;
} /**
* @param urlStr
* 请求的地址
* @param content
* 请求的参数 格式为:name=xxx&pwd=xxx
* @param encodingString
* 服务器端请求编码。如GBK,UTF-8等
* @return
*/
private static String getResult(String urlStr, String content, String encodingString) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
// 新建连接实例
connection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间,单位毫秒
//connection.setConnectTimeout(20000);
// 设置读取数据超时时间,单位毫秒
//connection.setReadTimeout(20000);
//是否打开输出流
connection.setDoOutput(true);
//是否打开输入流
connection.setDoInput(true);
//提交方法 POST|GET
connection.setRequestMethod("POST");
//是否缓存
connection.setUseCaches(false);
//打开连接端口
connection.connect();
//打开输出流往对端服务器写数据
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//写数据,即提交表单 name=xxx&pwd=xxx
out.writeBytes(content);
//刷新
out.flush();
//关闭输出流
out.close();
// 往对端写完数据对端服务器返回数据 ,以BufferedReader流来读取
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encodingString));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
}
return null;
}
}
测试:
@Test
public void getAddressByIp() throws Exception {
// 参数ip
String ip = "219.136.134.157";
// json_result用于接收返回的json数据
String json_result = null;
try {
json_result = AddressUtils.getAddresses("ip=" + ip, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONObject json = JSONObject.fromObject(json_result);
System.out.println("json数据: " + json);
String country = JSONObject.fromObject(json.get("data")).get("country").toString();
String region = JSONObject.fromObject(json.get("data")).get("region").toString();
String city = JSONObject.fromObject(json.get("data")).get("city").toString();
String county = JSONObject.fromObject(json.get("data")).get("county").toString();
String isp = JSONObject.fromObject(json.get("data")).get("isp").toString();
String area = JSONObject.fromObject(json.get("data")).get("area").toString();
System.out.println("国家: " + country);
System.out.println("地区: " + area);
System.out.println("省份: " + region);
System.out.println("城市: " + city);
System.out.println("区/县: " + county);
System.out.println("互联网服务提供商: " + isp); String address = country + "/";
address += region + "/";
address += city + "/";
address += county;
System.out.println(address);
结果:
{"code":0,"data":{"country":"中国","country_id":"CN","area":"华南","area_id":"800000","region":"广东省","region_id":"440000","city":"广州市","city_id":"440100","county":"越秀区","county_id":"440104","isp":"电信","isp_id":"100017","ip":"219.136.134.157"}}
国家: 中国
地区: 华南
省份: 广东省
城市: 广州市
区/县: 越秀区
互联网服务提供商: 电信
中国/广东省/广州市/越秀区
但用淘宝的API时,真的很慢,少量数据还可以,一旦数据上万,那就结束不了了,等了好久都运行不完。
没办法,开始尝试其他方法。
用【GeoLite2 City】库(源自:Java 通过Request请求获取IP地址对应省份、城市)
pom.xml:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.1</version>
</dependency>
测试:
public static void main(String[] args) throws IOException{
// 创建 GeoLite2 数据库
File database = new File("/Users/admin/GeoLite2-City.mmdb");
// 读取数据库内容
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("171.108.233.157");
// 获取查询结果
CityResponse response = null;
try {
response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'CN'
System.out.println(country.getName()); // 'China'
System.out.println(country.getNames().get("zh-CN")); // '中国'
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Guangxi Zhuangzu Zizhiqu'
System.out.println(subdivision.getIsoCode()); // '45'
System.out.println(subdivision.getNames().get("zh-CN")); // '广西壮族自治区'
// 获取城市
City city = response.getCity();
System.out.println(city.getName()); // 'Nanning'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // 'null'
System.out.println(city.getNames().get("zh-CN")); // '南宁'
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 22.8167
System.out.println(location.getLongitude()); // 108.3167
} catch (GeoIp2Exception e) {
e.printStackTrace();
}
}
这个就很快了,不过只能获取到城市。
Java 根据IP获取地址的更多相关文章
- java 通过ip获取客户端mac地址
java 通过ip获取客户端mac地址 package com.asppro.util; import java.io.BufferedReader; import java.io.IOExcepti ...
- 如何根据Ip获取地址信息--Java----待整理完善!!!
如何根据Ip获取地址信息--Java----待整理完善!!! QQWry.dat数据写入方法: http://www.cnblogs.com/xumingxiang/archive/2013/02/1 ...
- java-通过ip获取地址
添加maven依赖 <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all&l ...
- C#调用百度高精度IP定位API通过IP获取地址
API首页:http://lbsyun.baidu.com/index.php?title=webapi/high-acc-ip 1.申请百度账号,创建应用,获取密钥(AK) http://lbsyu ...
- PHP 中根据 IP 获取地址
这里使用的是淘宝 IP 地址库提供的 API 接口. 淘宝 IP 地址库:http://ip.taobao.com/instructions.html API 文档说明: 使用事例: /** * 调 ...
- 几种获取IP 根据IP获取地址的方法 JS,第三方 新浪 网易 腾讯
第一种是利用纯真ip数据库,这个可以在网上找到很多,缺点是更新有点慢. 第二种是利用门户网站的接口 目前已知的有腾讯.新浪.网易.搜狐和Google提供IP地址查询API,但是找得到的只有腾讯.新浪和 ...
- java 根据ip获取地区信息(淘宝和新浪)
package com.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStr ...
- 通过ip获取地址
<?php /** * IP 地理位置查询类 * * @author 马秉尧 * @version 1.5 * @copyright 2005 CoolCode.CN */ class IpLo ...
- python通过ip获取地址
# -*- coding: utf-8 -*- url = "http://ip.taobao.com/service/getIpInfo.php?ip=" #查找IP地址 def ...
随机推荐
- Elements in iteration expect to have 'v-bind:key' directives.' 提示错误如何解决?
在学习vue过程中遇到Elements in iteration expect to have 'v-bind:key' directives.' 这个错误,查阅资料得知Vue 2.2.0+的版本里, ...
- 使用python获取网易云音乐无损音频教程
博客园主页:http://www.cnblogs.com/handoing/ github项目:https://github.com/handoing/get-163-music 环境:Python ...
- ejs模板在express里的默认文件夹路径修改
默认的是这句: app.set('view engine','ejs') ===>/views文件夹 我想要变成/websong app.set('views','webosg'); app.s ...
- Nginx+PHP “No input file specified”错误的解决办法
配置官网商城php网站时候,界面报错“No input file specified” 原理: 任何对.php文件的请求,都简单地交给php-cgi去处理,但没有验证该php文件是否存在. PHP文件 ...
- 剑指offer-判断是否是平衡二叉树
private boolean isBalanced = true; public boolean IsBalanced_Solution(TreeNode root) { height(root); ...
- cookies和session区别
session原理:1.session是保存在服务器端,理论上是没有是没有限制,只要你的内存够大 2.浏览器第一次访问服务器时会创建一个session对象并返回一个JSESSIONID=ID的值, ...
- 洛谷——P2799 国王的魔镜
P2799 国王的魔镜 题目描述 国王有一个魔镜,可以把任何接触镜面的东西变成原来的两倍——只是,因为是镜子嘛,增加的那部分是反的.比如一条项链,我们用AB来表示,不同的字母表示不同颜色的珍珠.如果把 ...
- leetcode7 Rerver Integer
题意:数字反转 思路:醉了,提交了好几次,难点不在于怎么反转,而是判断是否益处,原题中给的是int,4个字节,32位,开始不知道怎么判断.现在知道了是limits.h中的INT_MIN和INT_MAX ...
- python 打包详解
基本步骤: 1. 写setup.py 2. 运行“python setup.py sdist” 3. 在当前目录下会生成文件夹“dist”,打包好的代码就在dist中,以“.tar.gz”的形式被压缩 ...
- 【BZOJ 2744】 2744: [HEOI2012]朋友圈 (最大团,二分图匹配,构图)
2744: [HEOI2012]朋友圈 Description 在很久很久以前,曾经有两个国家和睦相处,无忧无虑的生活着.一年一度的评比大会开始了,作为和平的两国,一个朋友圈数量最多的永远都是最值得他 ...