java 下载图片流
昨天在做日常时碰到了一个问题:根据图片的URL地址,返回该图片文件的byte数据。
第一种方案:通过HttpURLConnection创建连接,然后,从该连接获取图片流。
1 public class ImageReaderUtil {
2 /**
3 * @param
4 * imageUrl
5 * @return
6 * byte array of the file
7 */
8 public static byte[] getBytesByURL(String imageUrl)throws IOException {
9 ByteArrayOutputStream baos = new ByteArrayOutputStream();
10 BufferedInputStream bis = null;
11 HttpURLConnection urlconnection= null;
12 URL url = null;
13 byte[] buf = new byte[1024];
14 try {
15 url = new URL(imageUrl);
16 urlconnection = (HttpURLConnection) url.openConnection();
17 urlconnection.connect();
18 bis = new BufferedInputStream(urlconnection.getInputStream());
19 for (int len = 0; (len = bis.read(buf)) != -1;){
20 baos.write(buf,0,len);
21 }
22 return baos.toByteArray();
23 } finally {
24 try {
25 urlconnection.disconnect();
26 bis.close();
27 } catch (IOException ignore) {
28 }
29 }
30 }
31 }
第二种方案:通过httpClient下载
package com.ustc.java.io;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class DownLoadPicture {
public DownLoadPicture() {
super();
// TODO Auto-generated constructor stub
}
public byte[] downLoad(String imgURL){
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 创建GET方法的实例
GetMethod getMethod = new GetMethod(imgURL);
// 使用系统提供的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
try {
// 执行getMethod
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "+ getMethod.getStatusLine());
}
// 读取内容
byte[] responseBody = getMethod.getResponseBody();
return responseBody;
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
e.printStackTrace();
} finally {
// 释放连接
getMethod.releaseConnection();
}
return null;
}
public static void main(String[] args) {
String picture="http://upload3.mop.com/upload3/2009/06/27/02/1246083475154.jpg";
new DownLoadPicture().downLoad(picture);
}
}
需要注意的是,要是通过这种方法下载图片的byte流,则需要增加三个jar包:commons-logging,commons-httpclient,commons-codec
参考资料:http://www.ibm.com/developerworks/cn/opensource/os-httpclient/#ibm-pcon

浙公网安备 33010602011771号