package com.imooc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
/*
* 使用URL读取网页内容
*/
public class test03 {
public static void main(String[] args) {
try {
//创建一个URL实例
URL url=new URL("http://www.baidu.com");
//通过URL的openStream方法获取URL对象所标示的资源的字节输入流
InputStream is=url.openStream();
//将字节输入流转换为字符输入流
InputStreamReader isr=new InputStreamReader(is,"utf-8");
//为字符输入流添加缓冲
BufferedReader br= new BufferedReader(isr);
String date=br.readLine();
while(date!=null){
System.out.println(date);
date=br.readLine();
is.close();
}
br.close();
isr.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}这下面是报错
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.ensureOpen(HttpURLConnection.java:3348)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3373)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.imooc.test03.main(test03.java:29)
说出来你可能不信, 你少打了一个“}", 我打了就输出了乱码
亲爱的,我刚刚查了一下你的代码,是倒数第2行少了一个花括号“ } ”,其余都没问题。
你试试~~