Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Java中的IP地址查找城市名称_Java_Location_Ip - Fatal编程技术网

如何使用Java中的IP地址查找城市名称

如何使用Java中的IP地址查找城市名称,java,location,ip,Java,Location,Ip,我想从IP地址使用Java的城市名称 有什么想法可以这样做吗?来自Andrey link,这里是如何构造查询,此代码将返回一个HTML文件,其中包含当前IP的所有详细信息,包括城市 String IP= "123.123.123.123"; URL link = new URL("http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="+IP); BufferedReader

我想从IP地址使用Java的城市名称


有什么想法可以这样做吗?

来自Andrey link,这里是如何构造查询,此代码将返回一个HTML文件,其中包含当前IP的所有详细信息,包括城市

String IP= "123.123.123.123";
URL link = new URL("http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="+IP);

BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
String inputLine;

while ((inputLine = in.readLine()) != null){
     System.out.println(inputLine);             
}

in.close();
更新,2013年5月23日

前面的答案是可以的,但它不是一个API调用,它读取一个HTML页面,这是我之前提供的,因为我没有找到任何免费的API。接下来是一个可以轻松使用的REST API调用,它将返回所需的所有信息,建议使用此调用:

String ip = "2.51.255.200"; 
URL url = new URL("http://freegeoip.net/csv/" + ip);
connection = (HttpURLConnection) url.openConnection();
connection.connect();

InputStream is = connection.getInputStream();

int status = connection.getResponseCode();
if (status != 200) {
    return null;
}

reader = new BufferedReader(new InputStreamReader(is));
for (String line; (line = reader.readLine()) != null;) {
    //this API call will return something like:
    "2.51.255.200","AE","United Arab Emirates","03","Dubai","Dubai","","x-coord","y-coord","",""
    // you can extract whatever you want from it
}

如果您的应用程序部署在防火墙后面。因此,我们可以使用GeoLite来代替调用API,下面是示例代码

从下载City.dat文件


这已经被问了很多。请在发布前尝试搜索。这与编程无关。。。没有任何语言可以帮助你做到这一点,你可以查询数据源来获取这些信息,这可以是一个网站、一个数据库、一个xml服务等等。@Numenor:这绝对、完全、完全和编程相关。你的评论毫无意义。@WizardOfOdds:想象一下“我想要使用Java的国家的城市名称”是关于编程的吗?不,这是关于查询可用于获取此信息的数据源。Tushar在这里问他从哪里获得数据来获取IP地址信息,而不是如何编程,他的答案是由ANdrey提供的,它是一个url…@Numenor:ANdrey和medopal的答案是建设性的。不是你的。谁会像medopal那样使用Andrey提供的URL?屠夫?医生?护士?你,努梅诺爵士,身体严重不适,还不太明白这是怎么回事。想要使用Java中的IP地址查找城市名称是一个与编程相关的问题。更新2020?freegeoip已关闭,我正在使用它提供免费和付费订阅。
            File    datapath = new File("GeoLiteCity.dat");
            LookupService cl = new LookupService(datapath,
                    LookupService.GEOIP_MEMORY_CACHE
                            | LookupService.GEOIP_CHECK_CACHE);
            String cityName = cl.getLocation(ipAddress).city;