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