java运用URLConnection类以正确的字符集下载一个web页面
时间: 2024-06-10 20:05:17 浏览: 9
可以通过以下代码来实现:
```java
import java.io.*;
import java.net.*;
public class DownloadWebPage {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
File file = new File("output.html");
FileWriter fw = new FileWriter(file);
fw.write(sb.toString());
fw.close();
System.out.println("Web page downloaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们通过`URLConnection`类打开一个URL连接,并设置请求头的`User-Agent`属性。接着,我们从连接中获取输入流,然后使用`BufferedReader`类读取该流中的内容。读取完成后,我们将内容写入一个文件中,以便后续使用。
其中,`InputStreamReader`类的第二个参数用于指定正确的字符集。在这个例子中,我们使用的是`UTF-8`编码。