Spring Boot发送http请求

因为项目要调用第三方网站接口获取信息(类似python爬虫),所以在后端项目中需要前端axios一样去构建请求获取信息。下面用简单的获取IP地址为例。

java 复制代码
@Slf4j
public class IPTest {

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "未知地址";

    private String getRealAddressByIP(String ip) {
        String address = UNKNOWN;

        if (true) {
            try {
                String rspStr = sendGet(IP_URL, "ip=" + ip + "&json=true" ,"GBK");
                if (StrUtil.isEmpty(rspStr)) {
                    return UNKNOWN;
                }
                JSONObject obj = JSONObject.parseObject(rspStr);
                String addr = obj.getString("addr");
                return String.format("%s" , addr);
            } catch (Exception e) {
            }
        }
        return address;
    }


     private String sendGet(String url, String param, String contentType) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept" , "*/*");
            connection.setRequestProperty("connection" , "Keep-Alive");
            connection.setRequestProperty("User-Agent","Mozilla/4.0 compatible; MSIE 6.0; Windows NT 5.1;DigExt");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (ConnectException e) {   
        } catch (SocketTimeoutException e) {
        } catch (IOException e) {
        } catch (Exception e) {
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
            }
        }
        return result.toString();
    }


    public static void main(String[] args) {
        String ipaddr = getRealAddressByIP(你的ip);
        String address = ipaddr.equals("未知地址") ? "位置获取失败" : ipaddr;
        log.info(address);
    }
}

有些网站会做反爬机制,所以在创建URL的时候,加上这句 connection.setRequestProperty("User-Agent","Mozilla/4.0 compatible; MSIE 6.0; Windows NT 5.1;DigExt");可以解决大部分问题

相关推荐
刘一说7 小时前
深入理解 Spring Boot 的 @ConfigurationProperties:配置绑定机制与最佳实践
java·spring boot·spring
QWQ___qwq7 小时前
Spring Boot + Spring Security + JWT 登录认证完整实现
spring boot·spring·状态模式
loading小马7 小时前
解决idea2024版本Services栏没有显示Springboot窗口问题
java·spring boot·后端
好学且牛逼的马7 小时前
Spring Boot 3 核心实战指南
java·spring boot·后端
却道天凉_好个秋7 小时前
WebRTC(十五):NAT穿透机制深度解析
后端·webrtc·stun·turn·ice·net网络穿透
uzong7 小时前
职场上要懂的思维模型系列(第一章)
后端
代码探秘者7 小时前
【Redis】双写一致性:延迟双删 / 读写锁 / 异步通知 / Canal,一文全解
java·数据库·redis·后端·算法·缓存
身如柳絮随风扬7 小时前
Apache POI导出Word,PPT完整实现
spring boot·word·powerpoint·apache
IT枫斗者7 小时前
CentOS 7 一键部署 K8s 1.23 + Rancher 2.7 完整指南
java·linux·spring boot·后端·kubernetes·centos·rancher
ding_zhikai7 小时前
【Web应用开发笔记】Django笔记8:用户账户相关功能
笔记·后端·python·django