如何用Java写一个访问URL并获取信息和状态码

博客仅提及结果截图,但未给出更多关键信息。推测可能是关于某信息技术成果的截图呈现,不过缺乏具体内容难以进一步明确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.wonders.commonweb.core.utils;

import com.expansion.postUtils.PostUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

public class postUtils {

    public static String getUrlCode(String surl){
        String code=null;
        try {
            URL url = new URL(surl);
            URLConnection rulConnection   = url.openConnection();
            HttpURLConnection httpUrlConnection  =  (HttpURLConnection) rulConnection;
            httpUrlConnection.setConnectTimeout(300000);
            httpUrlConnection.setReadTimeout(300000);
            httpUrlConnection.connect();
            code = new Integer(httpUrlConnection.getResponseCode()).toString();
            String message = httpUrlConnection.getResponseMessage();
            System.out.println("getResponseCode code ="+ code);
            System.out.println("getResponseMessage message ="+ message);
            if(!code.startsWith("2")){
                throw new Exception("ResponseCode is not begin with 2,code="+code);
            }
            System.out.println("连接"+surl+"正常");
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        return code;

    }
    public static void main(String[] args) {
        String surl="https://www.baidu.com/";
        System.out.println(getUrlCode(surl));
    }
}

结果截图:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值