我希望使用Java从IP地址获取城市名称
有什么想法吗?
从Andrey链接,这里是如何构建查询,此代码将返回一个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 }