java代码访问网页

复制代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
public class WebPageAccess {
    public static void main(String[] args) {
        String url = "http://example.com"; // 输入要访问的网页链接
        
        try {
            // 创建URL对象
            URL link = new URL(url);
            
            // 创建HttpURLConnection对象
            HttpURLConnection connection = (HttpURLConnection) link.openConnection();
            
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            
            // 发送GET请求
            int responseCode = connection.getResponseCode();
            
            // 判断请求是否成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取返回的内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuffer response = new StringBuffer();
                
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                
                // 打印返回的内容
                System.out.println(response.toString());
            } else {
                System.out.println("请求失败,响应代码:" + responseCode);
            }
            
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
复制代码

 

posted @   ASKANDANSWERS  阅读(22615)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示