import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class IPLocation {
public static String getRegionByIP(String ipAddress) {
String url = "http://ip-api.com/json/" + ipAddress;
String region = "Unknown";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String jsonResponse = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(jsonResponse);
region = json.getString("regionName");
}
} catch (Exception e) {
e.printStackTrace();
}
return region;
}
public static void main(String[] args) {
// 示例:通过IP地址获取地区
String ip = "8.8.8.8"; // Google的公共DNS服务器IP地址
System.out.println("IP地址 " + ip + " 所在的地区是: " + getRegionByIP(ip));
}
}
org.apache.http 和 org.json 库来发送HTTP请求并解析JSON响应。你需要确保这些库已添加到你的项目中。http://ip-api.com/json/ API 获取对应的地区信息。API返回的结果是一个JSON格式的字符串,我们从中提取出 regionName 字段作为地区名称。getRegionByIP 方法。如果你无法找到相关代码或API,请确保你已经正确配置了所需的库和依赖项。
上一篇:java断言怎么用
下一篇:java匿名函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站