在日常開發中,加載網絡圖檔是一個常見的需求,而網上也有很多加載圖檔的架構,Picasso是目前比較流行的一款加載圖檔架構,它最簡單的使用方法如下。
picasso.load(url).into(imageView);
但是這個請求url送出的請求與之前的請求就不在同一個會話上 ,如果我們需要讓請求保持在同一個會話上,我們應該先定義個攔截器。該攔截器傳回一個帶Response,這個對象的請求頭已經設定好我們想要的cookie了。
package com.zhang.oa.Interceptor;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class RequestInterceptor implements Interceptor {
String cookie = null;
public RequestInterceptor(String cookie) {
this.cookie = cookie;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder request = chain.request().newBuilder();
request.addHeader("Cookie", cookie);
return chain.proceed(request.build());
}
}
接着在onCreate中編寫代碼實作網絡圖檔的加載。
//加載網絡圖檔
final OkHttpClient okHttpClient = new OkHttpClient();
//設定請求頭,在同一個session
okHttpClient.interceptors().add(new RequestInterceptor(getSharedPreferences("identify", Context.MODE_PRIVATE).getString("sessionId",null)));
Picasso picasso = new Picasso.Builder(YZSQFJXQActivity.this).downloader(new OkHttpDownloader(okHttpClient)).build();
picasso.load(url).into(imageView);
其中url為我們後端開發好的請求接口,imageView為前端的ImageView對象。
有些時候,我們需要通過架構來擷取圖檔的位圖(Bitmap)進而可以進行檔案的本地儲存,Picasso架構也提供了這一功能,代碼如下。
final OkHttpClient okHttpClient = new OkHttpClient();
//設定請求頭,在同一個session
okHttpClient.interceptors().add(new RequestInterceptor(getSharedPreferences("identify", Context.MODE_PRIVATE).getString("sessionId",null)));
final Picasso picasso = new Picasso.Builder(YZSQFJXQActivity.this).downloader(new OkHttpDownloader(okHttpClient)).build();
new Thread(new Runnable() {
@Override
public void run() {
try{
//擷取網絡圖檔的位圖
imageBitmap = picasso.load(url).get();
handler.sendEmptyMessage(0);
}
catch (Exception e){e.printStackTrace();}
}
}).start();
這樣就可以擷取網絡資源的位圖了,擷取位圖後可以調用ImageView中的setImageBitmap進行圖檔的設定。
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int tag = msg.what;
switch (tag) {
//擷取資料
case 0:
//設定位圖
imageView.setImageBitmap(imageBitmap);
break;
}
}
};
有了Bitmap後還可以進行圖檔的本地儲存等功能。