[转载]HttpClient的下载

作者: ldsea 分类: 程序生活 发布时间: 2009-04-11 16:57

下载页面文件

[code]import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class GetPageExample {
public static void main( String[] args ) {
   if( args.length() == 0 ) {
    System.out.println( "Usage: java GetPageExample URL" );
    System.exit( 0 );
   }
   String url = args[ 0 ];
   try {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod( url );
    method.setFollowRedirects( true );

    // Execute the GET method
    int statusCode = client.executeMethod( method );
    if( statusCode != -1 ) {
      String contents = method.getResponseBodyAsString();
      method.releaseConnection();
      System.out.println( contents );
    }
   }
   catch( Exception e ) {
    e.printStackTrace();
   }
}
}[/code]
下载文件

[code]import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class GetFileExample {
public static void main( String[] args ) {
   if( args.length() < 2 ) {
    System.out.println( "Usage: java GetFileExample URL filename" );
    System.exit( 0 );
   }
   String url = args[ 0 ];
   try {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod( url );
    method.setFollowRedirects( true );

    // Execute the GET method
    int statusCode = client.executeMethod( method );
    if( statusCode != -1 ) {
      System.out.println( "Reading file" );
      InputStream is = method.getResponseBodyAsStream();
      BufferedInputStream bis = new BufferedInputStream( is );
      FileOutputStream fos = new FileOutputStream( filename );
      byte[] bytes = new byte[ 8192 ];
      int count = bis.read( bytes );
      while( count != -1 && count <= 8192 ) {
       System.out.print( "-" );
       fos.write( bytes, 0, count );
       count = bis.read( bytes );
      }
      if( count != -1 ) {
       fos.write( bytes, 0, count );
      }
      fos.close();
      bis.close();
      method.releaseConnection();
      System.out.println( "\nDone" );    
    }
   }
   catch( Exception e ) {
    e.printStackTrace();
   }
}
}[/code]

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注