---
title: "HttpClient 实现下载图片"
author: "fenglin"
date: "2008-04-23T00:26:55Z"
tags: ["Apache", "C", "C#", "C++", "Java"]
slug: "httpclient"
draft: false
lastmod: "2008-04-23T00:26:55Z"
id: 185678
url: "https://fenglin.iteye.com/blog/185678"
---

最近在项目中用到了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类库的经验!