LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 719|回复: 2

java 小例子[转贴]

[复制链接]
发表于 2004-1-23 00:43:33 | 显示全部楼层 |阅读模式

  1. import java.io.*;
  2. import java.net.*;

  3. public class URLClient{
  4.         protected URLConnection connection;
  5.        
  6.         public static void main(String[] args){
  7.                 URLClient client = new URLClient();
  8.                 String yahoo = client.getDocumentAt("http://www.yahoo.com");
  9.                 System.out.println(yahoo);
  10.         }
  11.         public String getDocumentAt(String urlString){
  12.                 StringBuffer document = new StringBuffer();
  13.                 try{
  14.                         URL url = new URL(urlString);
  15.                         URLConnection conn = url.openConnection();
  16.                         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  17.                        
  18.                         String line = null;
  19.                         while((line = reader.readLine()) != null)
  20.                                 document.append(line + "\n");
  21.                         reader.close();
  22.                 }catch(MalformedURLException e){
  23.                         System.out.println("Unable to connect to URL:" + urlString);
  24.                 }catch(IOException e){
  25.                         System.out.println("IOException when connecting to URL:" + urlString);
  26.                 }
  27.                 return document.toString();
  28.         }
  29. }
复制代码
发表于 2004-1-24 18:13:34 | 显示全部楼层
来个perl的列子:

  1. #! /usr/bin/perl -w

  2. use LWP::Simple;

  3. $doc = get("http://www.yahoo.com");
  4. print $doc;
复制代码
发表于 2004-1-27 09:01:39 | 显示全部楼层
最好把url处改成静态方法,对于多处调用可以很好的提高性能,而不需要再创建新对象!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表