利用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;??
- ????????}??
- ????}??
- 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();??
- ????}??
- }??
common-logging.jar,
common-codec.jar,
common-collection.jar,
commons-beanutils.jar
还有其他的类库,自己运行时看缺那个类吧,自己找一下 4 楼 java_mid4 2007-12-04 以前用过这玩意儿去抓别人网站上的数据。。。