利用HttpClient下载图片

最近在项目中用到了HttpClient类库,有一个需求是下载网站中的图片,但是发现下载的图片不能打开,在网上搜索类似问题,没有找到解决的办法,无奈只得查看HttpClient的源代码,自己解决这个问题了。 在HttpMethodBase中发现如下代码: java 代码 public String getResponseBodyAsString() throws IOException { byte[] rawdata = null; if (responseAvailable()) { rawdata = getResponseBody(); } if (rawdata != null) { return EncodingUtil.getString(rawdata, getResponseCharSet()); } else { return null; } } 其中在返回网络资源的内容时,使用了指定的编码对网页内容或图片内容进行了编码,这样,对于图片来说内容当然不能显示了,所以在获得图片内容时要使用如下的方法: java 代码 public byte[] getResponseBody() throws IOException 或 public InputStream getResponseBodyAsStream() throws IOException 在把返回的内容存储到文件中,这样就实现了图片的自动下载,下面的代码演示了下载图片的过程 java 代码 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; /** * 用HttpClient下载图片 * @author wei */ public class TestDownImage { public static void main(String[] args) throws IOException{ HttpClient client = new HttpClient(); GetMethod get = new GetMethod("http://images.sohu.com/uiue/sohu_logo/beijing2008/2008sohu.gif"); client.executeMethod(get); File storeFile = new File("c:/2008sohu.gif"); FileOutputStream output = new FileOutputStream(storeFile); //得到网络资源的字节数组,并写入文件 output.write(get.getResponseBody()); output.close(); } } HttpClient是Apache组织的一个项目,作为Http客户端类库,功能十分强大,正在关注这个项目中,欢迎大家和我交流使用HttpClient类库的经验!
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值