您的位置:首页 > 编程语言 > Java开发

通过Java访问指定url

2010-12-12 22:41 316 查看
通过Java的 URL、URLConnection可以获取指定url的 html文件

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

注意:

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

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

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

codes:

PrintWriter out=null;
try {
out = new PrintWriter( location+folder+"/video/index.html","UTF-8" );
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

URL url=null;
try {
//这是新闻的主页,要根据部署的服务器url,修改
url = new URL("http://localhost/MySite/video.do?method=showAllByWatcher&uid="+uid);
} catch (MalformedURLException e) {
e.printStackTrace();
}
BufferedReader r=null;
try {
URLConnection con=url.openConnection();
r = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

String str="";
do{
try {
str=r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//			System.out.println(str);
out.println(str);
}while(str!=null);
out.flush();

out.close();
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: