說不清楚,直接看代碼吧
public class ImageNetService{
//http://p2.qhimg.com/t0112c0fd8f19123109.jpg
FileOutputStream fileOutputStream;
public ImageNetService(FileOutputStream fileOutputStream) {
super();
this.fileOutputStream = fileOutputStream; //不能new FileOutputStream ,而應該openFileOutput("gaoxiao.jpg", this.getContext().MODE_PRIVATE));
}
public void getNetImage() throws Throwable{
String s="http://p2.qhimg.com/t0112c0fd8f19123109.jpg";
URL url=new URL(s);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setConnectTimeout(10*1000);
connection.setRequestMethod("GET");
if(connection.getResponseCode()!=200){
throw new RuntimeException("請求URL無響應");
}
InputStream inputStream=connection.getInputStream();
byte[]result=readData(inputStream);
//File file=new File("gaoxiao.jpg"); //在javase環境下,是這樣寫的
//FileOutputStream fileOutputStream=new FileOutputStream(file);//這樣寫在安卓系統中報錯
fileOutputStream.write(result);
fileOutputStream.close();
}
public static byte[] readData(InputStream inputStream) throws Exception{
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=-1;
while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer, 0, len);
}
byte[]data=outputStream.toByteArray();
outputStream.close();
inputStream.close();
return data;
}
}