HttpClient关于下载的资料收集

HttpClient中下载模拟的资料如下:
在HttpMethodBase中发现如下代码:

java 代码
 
  1. public String getResponseBodyAsString() throws IOException {  
  2.         byte[] rawdata = null;  
  3.         if (responseAvailable()) {  
  4.             rawdata = getResponseBody();  
  5.         }  
  6.         if (rawdata != null) {  
  7.             return EncodingUtil.getString(rawdata, getResponseCharSet());  
  8.         } else {  
  9.             return null;  
  10.         }  
  11.     }  

其中在返回网络资源的内容时,使用了指定的编码对网页内容或图片内容进行了编码,这样,对于图片来说内容当然不能显示了,所以在获得图片内容时要使用如下的方法:

java 代码
 
  1. public byte[] getResponseBody() throws IOException   
  2. 或  
  3. public InputStream getResponseBodyAsStream() throws IOException  

在把返回的内容存储到文件中,这样就实现了图片的自动下载,下面的代码演示了下载图片的过程

java 代码
 
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4.   
  5. import org.apache.commons.httpclient.HttpClient;  
  6. import org.apache.commons.httpclient.methods.GetMethod;  
  7.   
  8. /** 
  9.  * 用HttpClient下载图片 
  10.  * @author wei 
  11.  */  
  12. public class TestDownImage {  
  13.       
  14.     public static void main(String[] args) throws IOException{  
  15.         HttpClient client = new HttpClient();  
  16.         GetMethod get = new GetMethod("http://images.sohu.com/uiue/sohu_logo/beijing2008/2008sohu.gif");  
  17.         client.executeMethod(get);  
  18.         File storeFile = new File("c:/2008sohu.gif");  
  19.         FileOutputStream output = new FileOutputStream(storeFile);  
  20.         //得到网络资源的字节数组,并写入文件  
  21.         output.write(get.getResponseBody());  
  22.         output.close();  
  23.     }  
  24. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值