下载图片我使用了两种方法,一,使用HttpURLConnection,下载图片;二,使用okhttp下载图片。大体操作为,首先,获得网络的输入流,然后得到Bitmap,再将bitmap写到文件中。
一、HttpURLConnection
public void downLoadPic_HurlConn(View view){
final Thread mythread=new Thread(new Runnable() {
@Override
public void run() {
byte []bytes=new byte[1024];
myaddr="http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg";
try {
myurl=new URL(myaddr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn= (HttpURLConnection) myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoInput(true);
conn.setDoOutput(true);
try {
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","Keep-Alive");
conn.connect();
if(conn.getResponseCode()==200){
inputStream=conn.getInputStream();
filepic=createPicFile();//得到需要保存的文件
outputStream=new FileOutputStream(filepic);
//错误的方法,可能会导致图片显示不全。我认为原因可能是解码或者格式不正确
// while(inputStream.read(bytes)!=-1){
// outputStream.write(bytes);
// }
//先得到bitmap,在得到bitmap的输出流output,在得到图片的字节数组,然后将其写到文件中
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream output=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,output);
byte[] pics=output.toByteArray();
outputStream.write(pics);
}else{
Log.i("LZH", String.valueOf(conn.getResponseCode()));
Log.i("LZH","connected fail");
return ;
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mythread.start();
}
二、OkHttp
public void OkHttp_get(View view){
OkHttpClient myclient=new OkHttpClient();
Request myrequest=new Request.Builder().
url("http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg").
build();
Call call=myclient.newCall(myrequest);
call.enqueue(new Callback() {
byte bytes[]=new byte[1024];
@Override
public void onFailure(Call call, IOException e) {
Log.i("LZH","okhttp fail");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
inputStream=response.body().byteStream();
filepic=createPicFile();
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream output=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,output);
byte[] pics=output.toByteArray();
outputStream=new FileOutputStream(filepic);
outputStream.write(pics);
}
});
}