代码如下:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class PrintPage {
public static void main(String[] args) {
String url_str="http://game.qq.com?ADTAG=media.innerenter.qqcom.indexnavigation";
new PrintPage().show(url_str);
}
public void show(String url_str){
URL url=null;
InputStream is=null;
URLConnection urlc=null;
BufferedReader br=null;
try {
url=new URL(url_str);
urlc=url.openConnection();
urlc.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1)  AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22");
is=urlc.getInputStream();
br=new BufferedReader(new InputStreamReader(is));
String temp="";
while((temp=br.readLine())!=null)
{
System.out.println(temp);
//Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行之后返回的结果如下:
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>
返回400 Bad Request,,这段代码用来打印别的页面没什么问题但打印代码里给的那个就出问题,,球解答URLJava

解决方案 »

  1.   

    url换为响应后的,http://game.qq.com/index.shtml
      

  2.   

    StringBuffer context = new StringBuffer();try {
    String line;
    URL url = new URL("http://game.qq.com?ADTAG=media.innerenter.qqcom.indexnavigation");
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    url.openStream(), "utf-8"));
    while ((line = reader.readLine()) != null) {
    if (!line.equals(""))
    context.append(line);
    }
    reader.close();网页的内容都在context里面了
      

  3.   


    需要知道网页的编码,有了编码在读取的时候设置下就不会乱了。最简单而有效的方法是读取网页的源码在meta节点里面有编码,用正则表达式提取出来,其他的都感觉不大好使。