1:ImageRequest 类
package com.capinfotech.net;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageRequest {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.eoeandroid.com/data/attachment/forum/201107/18/142935bbi8d3zpf3d0dd7z.jpg");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream inputStream = conn.getInputStream(); //通过输入流获得图片数据
byte[] getData = readInputStream(inputStream); //获得图片的二进制数据
File imageFile = new File("capinfotech.png");
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(getData);
fos.close();
System.out.println(" read picture success");
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
2:测试结果: 图片下载到项目的src目录下