不说啥 直接上代码:
public class WebPage {
HttpClient client;
public void getContent(String strUrl) throws IOException
{
client = new HttpClient();
GetMethod getMethod = new GetMethod("http://bbs.sjtu.edu.cn");
int statusCode = client.executeMethod( getMethod );
InputStream instream = getMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader( new InputStreamReader( instream, "utf-8"));
String line;
while( (line=br.readLine())!=null )
{
System.out.println( line );
}
getMethod.releaseConnection();
}
}
注意,通过把输入流转为对应的编码方式“utf-8”。显示即正常。
但同样是这套代码,把URL换成百度主页,又显示乱码。这是为什么呢?
看看网页返回的内容:
<meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>�ٶ�һ�£����֪�� </title><style>
为什么显示乱码,因为网页返回字符集为gb2312,而非utf-8。把获取网络流的编码方式修改后便显示正常。
注:以上代码用的HttpClient库,使用Java IO也是一样的道理,返回的流中一定要根据网页字符集进行相应转化。如此结果便能正常显示。
转载于:https://blog.51cto.com/imblues/807102