通过Java访问指定url

原文地址:点击打开链接

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

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

注意:

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

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

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

codes:

[java]  view plain copy
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值