android怎么获取用户所在地 csdn
5个回答
展开全部
三种方式进行定位,获取用户位置,分别是基于基站定位, 网络定位,GPS定位。
1.基站定位(passive):这是基于网络基站进行定位的,定位的精确度在几十米到几千米不等,在城市中基站覆盖率比较高,推荐使用基站定位,如果是在郊区,基站相距较远,基站的覆盖没有城里好,定位的误差比较大。如果在郊区不推荐使用基站定位。
2.网络定位:wifi定位,网络定位
3.GPS定位:与卫星进行通信。手机中嵌入了GPS模块(精简版的A-GPS),通过A-GPS搜索卫星, 获取经纬度。使用GPS的弊端是:必须站在空旷的地方,头顶对着天空,如果云层厚了,也会受到一定的影响。精确度:10-50米
扩展知识:
使用Android是定位必备的权限:
< uses-permission android:name= " android.permission.ACCESS_FINE_LOCATION " /> //精确定位
<uses-permission android:name= "android.permission.ACCESS_MOCK_LOCATION" /> //模拟器
<uses-permission android:name= "android.permission.ACCESS_COARSE_LOCATION" /> //粗糙定位
//获取定位管理对象
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);
String[] names=lm.getAllProviders();//获取所有的位置提供者,一般三种
Criteria criteria=new Criteria();//查询条件,如果设置了海拔,则定位方式只能是GPS;
criteria.setCostAllowed(true);//是否产生开销,比如流量费
String provider=lm.getBaseProvider(criteria,true)//获取最好的位置提供者,第二个参数为true,表示只获取那些被打开的位置提供者
lm.requestLocationUpdates(provier,0,0,new LocationListener(){});//获取位置。第二个参数表示每隔多少时间返回一次数据,第三个参数表示被定位的物体移动每次多少米返回一次数据。
private class MyLocationListener implements LocationListener {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
@Override
public void onLocationChanged(Location location) {
System. out.println( "服务中位置监听发送了变化了" );
float accuracy = location.getAccuracy(); // 精确度
double altitude = location.getAltitude(); // 海拔
double latitude = location.getLatitude(); // 纬度
double longitude = location.getLongitude(); // 经度
String locationInfo = "jingdu:" + longitude + ",weidu:" + latitude + ",haiba:" + altitude + ",jingquedu:" + accuracy;
Editor edit = sp.edit();
edit.putString( "location", locationInfo);
edit.commit();
}
} public void onProviderDisabled(String provider) {
}
展开全部
在很多生活类工具应用中都会包含用户位置信息,这样更方便的为用户服务。 经常我们使用三种方式进行定位,获取用户位置,分别是基于基站定位, 网络定位,GPS定位。
一:基站定位(passive):这是基于网络基站进行定位的,定位的精确度在几十米到几千米不等,在城市中基站覆盖率比较高,推荐使用基站定位,如果是在郊区,基站相距较远,基站的覆盖没有城里好,定位的误差比较大。如果在郊区不推荐使用基站定位。
二:网络定位:wifi定位,网络定位
运营商下放IP地址。比如彩虹QQ。
google纵横(统计一个非常大的IP和地址映射关系)
动态IP(IP池中随机获取一个IP地址,每次联网都会去池中获取一个随机的IP ,得到的是一个大体的地址),比如新浪微博。天气定位
方式三:GPS定位
与卫星进行通信。
手机中嵌入了GPS模块(精简版的A-GPS),通过A-GPS搜索卫星, 获取经纬度。
使用GPS的弊端是:必须站在空旷的地方,头顶对着天空,如果云层厚了,也会受到一定的影响。
精确度:10-50米
-------------------------------------------------------------------------------------------
使用Android是定位必备的权限:
< uses-permission android:name= " android.permission.ACCESS_FINE_LOCATION " /> //精确定位
<uses-permission android:name= "android.permission.ACCESS_MOCK_LOCATION" /> //模拟器
<uses-permission android:name= "android.permission.ACCESS_COARSE_LOCATION" /> //粗糙定位
//获取定位管理对象
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);
String[] names=lm.getAllProviders();//获取所有的位置提供者,一般三种
Criteria criteria=new Criteria();//查询条件,如果设置了海拔,则定位方式只能是GPS;
criteria.setCostAllowed(true);//是否产生开销,比如流量费
String provider=lm.getBaseProvider(criteria,true)//获取最好的位置提供者,第二个参数为true,表示只获取那些被打开的位置提供者
lm.requestLocationUpdates(provier,0,0,new LocationListener(){});//获取位置。第二个参数表示每隔多少时间返回一次数据,第三个参数表示被定位的物体移动每次多少米返回一次数据。
private class MyLocationListener implements LocationListener {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
System. out.println( "服务中位置监听发送了变化了" );
float accuracy = location.getAccuracy(); // 精确度
double altitude = location.getAltitude(); // 海拔
double latitude = location.getLatitude(); // 纬度
double longitude = location.getLongitude(); // 经度
String locationInfo = "jingdu:" + longitude + ",weidu:" + latitude + ",haiba:" + altitude + ",jingquedu:" + accuracy;
Editor edit = sp.edit();
edit.putString( "location", locationInfo);
edit.commit();
}
}
一:基站定位(passive):这是基于网络基站进行定位的,定位的精确度在几十米到几千米不等,在城市中基站覆盖率比较高,推荐使用基站定位,如果是在郊区,基站相距较远,基站的覆盖没有城里好,定位的误差比较大。如果在郊区不推荐使用基站定位。
二:网络定位:wifi定位,网络定位
运营商下放IP地址。比如彩虹QQ。
google纵横(统计一个非常大的IP和地址映射关系)
动态IP(IP池中随机获取一个IP地址,每次联网都会去池中获取一个随机的IP ,得到的是一个大体的地址),比如新浪微博。天气定位
方式三:GPS定位
与卫星进行通信。
手机中嵌入了GPS模块(精简版的A-GPS),通过A-GPS搜索卫星, 获取经纬度。
使用GPS的弊端是:必须站在空旷的地方,头顶对着天空,如果云层厚了,也会受到一定的影响。
精确度:10-50米
-------------------------------------------------------------------------------------------
使用Android是定位必备的权限:
< uses-permission android:name= " android.permission.ACCESS_FINE_LOCATION " /> //精确定位
<uses-permission android:name= "android.permission.ACCESS_MOCK_LOCATION" /> //模拟器
<uses-permission android:name= "android.permission.ACCESS_COARSE_LOCATION" /> //粗糙定位
//获取定位管理对象
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);
String[] names=lm.getAllProviders();//获取所有的位置提供者,一般三种
Criteria criteria=new Criteria();//查询条件,如果设置了海拔,则定位方式只能是GPS;
criteria.setCostAllowed(true);//是否产生开销,比如流量费
String provider=lm.getBaseProvider(criteria,true)//获取最好的位置提供者,第二个参数为true,表示只获取那些被打开的位置提供者
lm.requestLocationUpdates(provier,0,0,new LocationListener(){});//获取位置。第二个参数表示每隔多少时间返回一次数据,第三个参数表示被定位的物体移动每次多少米返回一次数据。
private class MyLocationListener implements LocationListener {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
System. out.println( "服务中位置监听发送了变化了" );
float accuracy = location.getAccuracy(); // 精确度
double altitude = location.getAltitude(); // 海拔
double latitude = location.getLatitude(); // 纬度
double longitude = location.getLongitude(); // 经度
String locationInfo = "jingdu:" + longitude + ",weidu:" + latitude + ",haiba:" + altitude + ",jingquedu:" + accuracy;
Editor edit = sp.edit();
edit.putString( "location", locationInfo);
edit.commit();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2015-01-10 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517196
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
最近在做一个互联网项目,不可避免和其他互联网项目一样,需要各种类似的功能。其中一个就是通过用户访问网站的IP地址显示当前用户所在地。在没有查阅资料之前,我第一个想到的是应该有这样的RESTFUL服务,可能会有免费的,也有可能会是收费的。后来查阅了相关资料和咨询了客服人员发现了一款相当不错的库:GEOIP。
首先来个Java 版本:
[java]
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
C#版本:
[csharp]
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
Ruby版本:
[ruby]
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
首先来个Java 版本:
[java]
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
C#版本:
[csharp]
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
Ruby版本:
[ruby]
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
最近在做一个互联网项目,不可避免和其他互联网项目一样,需要各种类似的功能。其中一个就是通过用户访问网站的IP地址显示当前用户所在地。在没有查阅资料之前,我第一个想到的是应该有这样的RESTFUL服务,可能会有免费的,也有可能会是收费的。后来查阅了相关资料和咨询了客服人员发现了一款相当不错的库:GEOIP。
首先来个Java 版本:
[java]
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
C#版本:
[csharp]
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
Ruby版本:
[ruby]
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
首先来个Java 版本:
[java]
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class OmniReader {
public static void main(String[] args) throws Exception {
String license_key = "YOUR_LICENSE_KEY";
String ip_address = "24.24.24.24";
String url_str = "http。//geoip。maxmind。com/e?l=" + license_key + "&i=" + ip_address;
URL url = new URL(url_str);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
// Alternatively use a CSV parser here.
Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
Matcher m = p.matcher(inLine);
ArrayList fields = new ArrayList();
String f;
while (m.find()) {
f = m.group(1);
if (f!=null) {
fields.add(f);
}
else {
fields.add(m.group(2));
}
}
String countrycode = fields.get(0);
String countryname = fields.get(1);
String regioncode = fields.get(2);
String regionname = fields.get(3);
String city = fields.get(4);
String lat = fields.get(5);
String lon = fields.get(6);
String metrocode = fields.get(7);
String areacode = fields.get(8);
String timezone = fields.get(9);
String continent = fields.get(10);
String postalcode = fields.get(11);
String isp = fields.get(12);
String org = fields.get(13);
String domain = fields.get(14);
String asnum = fields.get(15);
String netspeed = fields.get(16);
String usertype = fields.get(17);
String accuracyradius = fields.get(18);
String countryconf = fields.get(19);
String cityconf = fields.get(20);
String regionconf = fields.get(21);
String postalconf = fields.get(22);
String error = fields.get(23);
}
in.close();
}
}
C#版本:
[csharp]
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
private string GetMaxMindOmniData(string IP) {
System.Uri objUrl = new System.Uri("http。//geoip。maxmind。com/e?l=YOUR_LICENSE_KEY&i=" + IP);
System.Net.WebRequest objWebReq;
System.Net.WebResponse objResp;
System.IO.StreamReader sReader;
string strReturn = string.Empty;
try
{
objWebReq = System.Net.WebRequest.Create(objUrl);
objResp = objWebReq.GetResponse();
sReader = new System.IO.StreamReader(objResp.GetResponseStream());
strReturn = sReader.ReadToEnd();
sReader.Close();
objResp.Close();
}
catch (Exception ex)
{
}
finally
{
objWebReq = null;
}
return strReturn;
}
Ruby版本:
[ruby]
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = [:country_code,
:country_name,
:region_code,
:region_name,
:city_name,
:latitude,
:longitude,
:metro_code,
:area_code,
:time_zone,
:continent_code,
:postal_code,
:isp_name,
:organization_name,
:domain,
:as_number,
:netspeed,
:user_type,
:accuracy_radius,
:country_confidence,
:city_confidence,
:region_confidence,
:postal_confidence,
:error]
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new { |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
}.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
response = Net::HTTP.get_response(uri)
unless response.is_a?(Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni[:error]}"
else
puts
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
这个好像手机没有这个功能吧,最多就是通过软件定位....
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询