IP归属地 获取

直接上代码 (hutool 依赖)

<dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.7.3version>
dependency>
import cn.hutool.http.HttpUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("ip")
public class IpController {

    @GetMapping
    public String ip(HttpServletRequest request){
        // 一般项目会配置反向代理等,所以 x-forwarded-for 有时获取不到 用户真实地址
        // 故而 加上 Proxy-Client-IP,WL-Proxy-Client-IP (此两条为 apache 对 request 的封装)
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String str="http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true";
        String api = String.format(str, ip);
        String result = HttpUtil.get(api);
        return result;
    }
}

你可能感兴趣的:(java,初级,tcp/ip,java,网络协议)