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(); } } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/58312.html