[转载]HttpClient的下载 不指定

海蓝 , 2009/04/11 16:57 , Program Life - Java , 评论(0) , 阅读(1100) , Via 本站原创 | |
下载页面文件

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();
   }
}
}

下载文件

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();
   }
}
}
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]