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 ...
随机推荐
- 走进 Prism for Xamarin.Forms
一.使用环境 OS:Win 10 16273 VS:VS2017- 15.3.4 Xamarin:4.6.3.4,nuget:2.4 Android Emulator:Visual Studio fo ...
- JavaScript将最终获得正确的异步编程
JavaScript将最终获得正确的异步编程 包括该提案异步 在ECMAScript中的功能已经达到第四阶段; 这意味着它将在2017年发布的标准.但是这对JavaScript开发者意味着什么? 有很 ...
- ios 安卓 video 取消播放自动全屏 属性
x-webkit-airplay="true",x5-playsinline="true",webkit-playsinline="true" ...
- getAllResponseHeaders() 必须放到onload里面
<html><head> <meta charset="utf-8"> <title>test</title> < ...
- windows系统中,创建临时环境变量
以servlet-api.jar 包为例 set classpath=%classpath%;C:\apache-tomcat-6.0.37\lib\servlet-api.jar
- 19. Remove Nth Node From End of List【Medium】【删除单链表倒数第n个结点】
Given a linked list, remove the n-th node from the end of list and return its head. Example: Given l ...
- SpringBoot整合Quartz作为调度中心完整实用例子
因为想要做一个类似于调度中心的东西,定时执行一些Job(通常是一些自定义程序或者可执行的jar包),搭了一个例子,总结了前辈们的相关经验和自己的一些理解,如有雷同或不当之处,望各位大佬见谅和帮忙指正. ...
- python实现RabbitMQ同步跟异步消费模型
1,消息推送类 import pika # 同步消息推送类 class RabbitPublisher(object): # 传入RabbitMQ的ip,用户名,密码,实例化一个管道 def __in ...
- Matrix Zigzag Traversal(LintCode)
Matrix Zigzag Traversal Given a matrix of m x n elements (m rows, ncolumns), return all elements of ...
- Noip2015提高组解题报告
Day1 T1神奇的幻方 一道简单异常的小模拟,我们只需要确定数字1的位置,然后根据题意枚举即可,简简单单就A了,什么也不卡. 然而这题,我刚开始学OI的时候,因为当时比较蠢,被这题花式吊打啊.... ...