7 changed files with 77 additions and 11 deletions
@ -0,0 +1,46 @@ |
|||||
|
package com.bx.implatform.util; |
||||
|
|
||||
|
import cn.hutool.http.HttpRequest; |
||||
|
import cn.hutool.http.HttpResponse; |
||||
|
import cn.hutool.json.JSONObject; |
||||
|
import cn.hutool.json.JSONUtil; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
@Slf4j |
||||
|
@Component |
||||
|
@RequiredArgsConstructor |
||||
|
public class IpLocationUtil { |
||||
|
|
||||
|
private static final String IP_API_URL = "http://ip-api.com/json/{ip}?lang=zh-CN"; |
||||
|
|
||||
|
public String getIpLocation(String ip) { |
||||
|
try { |
||||
|
String url = IP_API_URL.replace("{ip}", ip); |
||||
|
|
||||
|
HttpResponse response = HttpRequest.get(url) |
||||
|
.timeout(5000) |
||||
|
.execute(); |
||||
|
|
||||
|
String body = response.body(); |
||||
|
JSONObject result = JSONUtil.parseObj(body); |
||||
|
|
||||
|
if (!"success".equals(result.getStr("status"))) { |
||||
|
log.warn("IP查询失败, ip:{}, res:{}", ip, body); |
||||
|
return ""; |
||||
|
} |
||||
|
|
||||
|
String country = result.getStr("country", ""); |
||||
|
String regionName = result.getStr("regionName", ""); |
||||
|
String city = result.getStr("city", ""); |
||||
|
|
||||
|
// 拼接中文地址
|
||||
|
return (country + " " + regionName + " " + city).trim(); |
||||
|
|
||||
|
} catch (Exception e) { |
||||
|
log.error("IP地理位置查询异常, ip:{}", ip, e); |
||||
|
return ""; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue