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(); } } }