利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = newURL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnectionconn =(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStreamis = conn.getInputStream();
readAsFile(is,"Img269812337.jpg");
public static void readAsFile(InputStreaminSream, File file) throws Exception{
FileOutputStreamoutStream =new FileOutputStream(file);
byte[] buffer =new byte[1024];
intlen =-1;
while( (len =inSream.read(buffer)) != -1 ){
outStream.write(buffer,0, len);
}
outStream.close();
inSream.close();
}