เนื่องจากมีโปรเจคท์นึง ที่ผมต้องเปิดรูปจากอินเตอร์เน็ตโดยใช้ Cookies เพื่อการเข้าถึงรูป เลยขอบันทึกไว้หน่อย เผื่อคราวหน้าจะต้องใช้อีก (อันนี้ทำแบบ Hard Code ค่า Cookies นะครับ ถ้าต้องการให้มันไปเอาค่ามาจากที่อื่น ก็ปรับโค้ดเอาเองนะครับ)
เริ่มแรก เพิ่มสิ่งเหล่านี้ลงใน dependencies ในไฟล์ build.gradle
dependencies {
....
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}
ดูจากสิ่งที่เราใส่เข้ามา ก็พอจะเดาได้ว่าในครั้งนี้ เราจะใช้ Picasso และ OkHttp3 Downloader กันนะครับ
การที่เราจะใช้งานอินเตอร์เน็ทนั้น เราต้องไปเพิ่ม Permission ที่ AndroidManifest.xml ด้วย
<uses-permission android:name="android.permission.INTERNET"/>
จากนั้นเราก็สร้าง Class สำหรับใส่ค่า Cookies ขอตั้งชื่อว่า CookieImageDownloader ซึ่ง extend มาจาก Class UrlConnectionDownloader ของ Picasso นะครับ
public class CookieImageDownloader extends UrlConnectionDownloader {
public CookieImageDownloader(Context context) {
super(context);
}
@Override
protected HttpURLConnection openConnection(Uri path) throws IOException {
HttpURLConnection conn = super.openConnection(path);
String cookieName = "ASP.NET_SessionId";
String cookieValue = "xxxxxxxxxxxxxxxxxxxxxxxx";
conn.setRequestProperty("Cookie",cookieName + "=" + cookieValue );
return conn;
}
}
ต่อไปก็เป็นการใช้งาน Class CookieImageDownloader นะครับ…
ก่อนอื่น สร้างตัวแปร Picasso ที่เรียกใช้งาน CookieImageDownloader ตามนี้
Picasso picasso = new Picasso.Builder(this)
.downloader(new CookieImageDownloader(this))
.build();
ต่อไป ก็ให้ picasso เรียกรูปจากอินเตอร์เน็ท โดยใส่ลิงค์ของรูปใน .load(url) และ ระบุ ImageView ที่ต้องการให้รูปแสดงที่ .into(imageView) ดังนี้
picasso.load("http://www.url.com/image.jpg")
.into(imageView);
คร่าว ๆ ตามนี้ละกัน มีคำถามอะไร คอมเม้นท์ถามได้ที่ช่องคอมเมนท์ด้านล่างนี้เลยครับ


