IP归属地信息查询代码示例(JAVA)
ip-v4
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
public class IPLocation {
public static void main(String[] args) {
String ip = "your_ip_address";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://ip-api.com/json/" + ip);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
JSONObject json = new JSONObject(EntityUtils.toString(entity))
System.out.println("Country: " + json.getString("country"));
System.out.println("Region: " + json.getString("regionName"));
System.out.println("City: " + json.getString("city"));
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ip-v6
获取IPv6位置的过程和上述IPv4的例子非常类似。只需要更改http://ip-api.com/json/为http://ipv6-test.com/api/,接口参数格式也几乎一样:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
public class IPV6Location {
public static void main(String[] args) {
String ip = "your_ipv6_address";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://ipv6-test.com/api/" + ip);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
JSONObject json = new JSONObject(EntityUtils.toString(entity))
System.out.println("Country: " + json.getString("country"));
System.out.println("Region: " + json.getString("regionName"));
System.out.println("City: " + json.getString("city"));
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}