通过Java访问指定url

来源:互联网 发布:淘宝账单生成器手机版 编辑:程序博客网 时间:2024/06/07 05:57

原文地址:点击打开链接

通过Java的 URL、URLConnection可以获取指定url的 html文件

可以实现静态化某些页面的功能。

注意:

在初始化 URL时,可以带参数,使用? &,规则和在浏览器一样

比如:            url = new URL("http://localhost/MySite/video.do?method=showAllByWatcher&uid="+uid);

ps:时常注意浏览器缓存,有时候很容易误导,以为是bug

codes:

[java] view plaincopy
  1. PrintWriter out=null;  
  2. try {  
  3.     out = new PrintWriter( location+folder+"/video/index.html","UTF-8" );  
  4. catch (FileNotFoundException e) {  
  5.     e.printStackTrace();  
  6. catch (UnsupportedEncodingException e) {  
  7.     e.printStackTrace();  
  8. }  
  9.   
  10. URL url=null;  
  11. try {  
  12.     //这是新闻的主页,要根据部署的服务器url,修改  
  13.     url = new URL("http://localhost/MySite/video.do?method=showAllByWatcher&uid="+uid);  
  14. catch (MalformedURLException e) {  
  15.     e.printStackTrace();  
  16. }  
  17. BufferedReader r=null;  
  18. try {  
  19.     URLConnection con=url.openConnection();  
  20.     r = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));  
  21. catch (UnsupportedEncodingException e1) {  
  22.     e1.printStackTrace();  
  23. catch (IOException e1) {  
  24.     e1.printStackTrace();  
  25. }  
  26.   
  27. String str="";  
  28. do{  
  29.     try {  
  30.         str=r.readLine();  
  31.     } catch (IOException e) {  
  32.         e.printStackTrace();  
  33.     }  
  34.             System.out.println(str);  
  35.     out.println(str);  
  36. }while(str!=null);  
  37. out.flush();  
  38.   
  39. out.close();  
  40. try {  
  41.     r.close();  
  42. catch (IOException e) {  
  43.     e.printStackTrace();  
  44. }  

 


0 0