ดูวิธีใช้ไลบรารี Cronet เพื่อดำเนินการด้านเครือข่ายในแอป Android ของคุณ Cronet คือสแต็กเครือข่าย Chromium ที่พร้อมใช้งานเป็นไลบรารีให้คุณใช้ในแอป ดูข้อมูลเพิ่มเติมเกี่ยวกับฟีเจอร์ของไลบรารีได้ที่ดำเนินการด้านเครือข่ายโดยใช้ Cronet
ตั้งค่าไลบรารีในโปรเจ็กต์
ทำตามขั้นตอนต่อไปนี้เพื่อเพิ่มทรัพยากร Dependency ลงในไลบรารี Cronet ในโปรเจ็กต์
ตรวจสอบว่า Android Studio มีการอ้างอิงถึงที่เก็บ Maven ของ Google ในไฟล์
settings.gradleของโปรเจ็กต์ ดังตัวอย่างต่อไปนี้ดึงดูด
dependencyResolutionManagement { ... repositories { ... google() } }
Kotlin
dependencyResolutionManagement { ... repositories { ... google() } }
ใส่ข้อมูลอ้างอิงถึงไลบรารีของไคลเอ็นต์บริการ Google Play สำหรับ Cronet ในส่วน
dependenciesของไฟล์build.gradleของโมดูลแอป ดังที่แสดงในตัวอย่างต่อไปนี้ดึงดูด
dependencies { implementation 'com.google.android.gms:play-services-cronet:18.0.1' }
Kotlin
dependencies { implementation("com.google.android.gms:play-services-cronet:18.0.1") }
ออบเจ็กต์ CronetEngine ที่สร้างขึ้นหลังจากที่คุณเพิ่มทรัพยากร Dependency นี้จะใช้ Cronet ที่โหลดจากบริการ Google Play เพื่อป้องกันข้อยกเว้นที่ไม่คาดคิดระหว่างการสร้าง CronetEngine (เช่น ในอุปกรณ์ที่ต้องใช้บริการ Google Play เวอร์ชันอัปเดต) ให้เรียกใช้ CronetProviderInstaller.installProvider(Context) ก่อนสร้างออบเจ็กต์ CronetEngine
ในกรณีที่ไม่สามารถโหลด Cronet จากบริการ Google Play ได้ จะมีการติดตั้งใช้งาน API ของ Cronet ที่มีประสิทธิภาพน้อยกว่าซึ่งสามารถใช้ได้ หากต้องการใช้การติดตั้งใช้งานสำรองนี้ ให้ใช้ org.chromium.net:cronet-fallback และเรียกใช้ new JavaCronetProvider(context).createBuilder()
สร้างคำขอเครือข่าย
ส่วนนี้แสดงวิธีสร้างและส่งคำขอเครือข่ายโดยใช้ไลบรารี Cronet หลังจากส่งคำขอเครือข่ายแล้ว แอปของคุณต้องประมวลผลการตอบกลับเครือข่าย
สร้างและกำหนดค่าอินสแตนซ์ของ CronetEngine
ไลบรารีมีคลาส CronetEngine.Builder ที่คุณใช้สร้างอินสแตนซ์ของ CronetEngine ได้ ตัวอย่างต่อไปนี้แสดงวิธีสร้างออบเจ็กต์ CronetEngine
Kotlin
val myBuilder = CronetEngine.Builder(context)
val cronetEngine: CronetEngine = myBuilder.build()
Java
CronetEngine.Builder myBuilder = new CronetEngine.Builder(context);
CronetEngine cronetEngine = myBuilder.build();
คุณสามารถใช้คลาส Builder เพื่อกำหนดค่าออบเจ็กต์ CronetEngine ได้ เช่น คุณสามารถระบุตัวเลือกต่างๆ เช่น การแคชและการบีบอัดข้อมูล ดูข้อมูลเพิ่มเติมได้ที่ CronetEngine.Builder
ระบุการใช้งาน Callback ของคำขอ
หากต้องการติดตั้งใช้งาน Callback ให้สร้างคลาสย่อยของ UrlRequest.Callback และติดตั้งใช้งานเมธอด Abstract ที่จำเป็น ดังที่แสดงในตัวอย่างต่อไปนี้
Kotlin
private const val TAG = "MyUrlRequestCallback"
class MyUrlRequestCallback : UrlRequest.Callback() {
override fun onRedirectReceived(request: UrlRequest?, info: UrlResponseInfo?, newLocationUrl: String?) {
Log.i(TAG, "onRedirectReceived method called.")
// You should call the request.followRedirect() method to continue
// processing the request.
request?.followRedirect()
}
override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) {
Log.i(TAG, "onResponseStarted method called.")
// You should call the request.read() method before the request can be
// further processed. The following instruction provides a ByteBuffer object
// with a capacity of 102400 bytes for the read() method. The same buffer
// with data is passed to the onReadCompleted() method.
request?.read(ByteBuffer.allocateDirect(102400))
}
override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) {
Log.i(TAG, "onReadCompleted method called.")
// You should keep reading the request until there's no more data.
byteBuffer?.clear()
request?.read(byteBuffer)
}
override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) {
Log.i(TAG, "onSucceeded method called.")
}
}
Java
class MyUrlRequestCallback extends UrlRequest.Callback {
private static final String TAG = "MyUrlRequestCallback";
@Override
public void onRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) {
Log.i(TAG, "onRedirectReceived method called.");
// You should call the request.followRedirect() method to continue
// processing the request.
request.followRedirect();
}
@Override
public void onResponseStarted(UrlRequest request, UrlResponseInfo info) {
Log.i(TAG, "onResponseStarted method called.");
// You should call the request.read() method before the request can be
// further processed. The following instruction provides a ByteBuffer object
// with a capacity of 102400 bytes for the read() method. The same buffer
// with data is passed to the onReadCompleted() method.
request.read(ByteBuffer.allocateDirect(102400));
}
@Override
public void onReadCompleted(UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) {
Log.i(TAG, "onReadCompleted method called.");
// You should keep reading the request until there's no more data.
byteBuffer.clear();
request.read(byteBuffer);
}
@Override
public void onSucceeded(UrlRequest request, UrlResponseInfo info) {
Log.i(TAG, "onSucceeded method called.");
}
}
สร้างออบเจ็กต์ Executor เพื่อจัดการงานเครือข่าย
คุณสามารถใช้คลาส Executor เพื่อเรียกใช้งานเครือข่ายได้ หากต้องการรับอินสแตนซ์ของ Executor ให้ใช้เมธอดแบบคงที่รายการใดรายการหนึ่งของคลาส Executors ที่แสดงผลออบเจ็กต์ Executor ตัวอย่างต่อไปนี้แสดงวิธีสร้างออบเจ็กต์ Executor โดยใช้เมธอด newSingleThreadExecutor()
Kotlin
val executor: Executor = Executors.newSingleThreadExecutor()
Java
Executor executor = Executors.newSingleThreadExecutor();
สร้างและกำหนดค่าออบเจ็กต์ UrlRequest
หากต้องการสร้างคำขอเครือข่าย ให้เรียกใช้เมธอด newUrlRequestBuilder() ของ CronetEngine โดยส่ง URL ปลายทาง อินสแตนซ์ของคลาส Callback และออบเจ็กต์ Executor เมธอด newUrlRequestBuilder() จะแสดงผลออบเจ็กต์ UrlRequest.Builder ที่คุณใช้สร้างออบเจ็กต์ UrlRequest ได้ ดังที่แสดงในตัวอย่างต่อไปนี้
Kotlin
val requestBuilder = cronetEngine.newUrlRequestBuilder(
"https://www.example.com",
MyUrlRequestCallback(),
executor
)
val request: UrlRequest = requestBuilder.build()
Java
UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder(
"https://www.example.com", new MyUrlRequestCallback(), executor);
UrlRequest request = requestBuilder.build();
คุณสามารถใช้คลาส Builder เพื่อกำหนดค่าอินสแตนซ์ของ UrlRequest ได้ เช่น คุณสามารถระบุลำดับความสำคัญหรือคำกริยา HTTP ได้ ดูข้อมูลเพิ่มเติมได้ที่
UrlRequest.Builder
หากต้องการเริ่มงานเครือข่าย ให้เรียกใช้เมธอด start() ของคำขอ ดังนี้
Kotlin
request.start()
Java
request.start();
คุณสามารถสร้างและส่งคำขอเครือข่ายโดยใช้ Cronet ได้โดยทำตามวิธีการในส่วนนี้ อย่างไรก็ตาม เพื่อความเรียบง่าย ตัวอย่างการติดตั้งใช้งาน UrlRequest.Callback จะพิมพ์เฉพาะข้อความไปยังบันทึกเท่านั้น
ส่วนต่อไปนี้แสดงวิธีระบุการใช้งาน Callback ที่รองรับสถานการณ์ที่เป็นประโยชน์มากขึ้น เช่น การดึงข้อมูลจากการตอบกลับและการตรวจหาความล้มเหลวในคำขอ
ประมวลผลการตอบกลับของเครือข่าย
หลังจากที่คุณเรียกใช้เมธอด start() แล้ว Cronet จะเริ่มวงจรคำขอ
จัดการคำขอระหว่างวงจรโดยระบุ Callback ดูข้อมูลเพิ่มเติมเกี่ยวกับวงจรได้ที่วงจรคำขอ Cronet คุณสามารถระบุ Callback ได้โดยสร้างคลาสย่อยของ UrlRequest.Callback และใช้เมธอดต่อไปนี้
onRedirectReceived()Cronet จะเรียกใช้เมธอดนี้เมื่อเซิร์ฟเวอร์ออกรหัสการเปลี่ยนเส้นทาง HTTP เพื่อตอบสนองต่อคำขอเดิม หากต้องการติดตามการเปลี่ยนเส้นทางไปยังปลายทางใหม่ ให้ใช้เมธอด
followRedirect()หรือใช้วิธีcancel()ตัวอย่างต่อไปนี้แสดงวิธีใช้เมธอดKotlin
override fun onRedirectReceived(request: UrlRequest?, info: UrlResponseInfo?, newLocationUrl: String?) { // Determine whether you want to follow the redirect. ... if (shouldFollow) { request?.followRedirect() } else { request?.cancel() } }Java
@Override public void onRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) { // Determine whether you want to follow the redirect. ... if (shouldFollow) { request.followRedirect(); } else { request.cancel(); } }onResponseStarted()Cronet จะเรียกใช้เมธอดนี้เมื่อได้รับชุดส่วนหัวสุดท้าย Cronet จะเรียกใช้
onResponseStarted()หลังจากติดตามการเปลี่ยนเส้นทางทั้งหมดแล้วเท่านั้น โค้ดต่อไปนี้แสดงตัวอย่างการใช้งานเมธอดKotlin
override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) { val httpStatusCode = info?.httpStatusCode if (httpStatusCode == 200) { // The request was fulfilled. Start reading the response. request?.read(myBuffer) } else if (httpStatusCode == 503) { // The service is unavailable. You should still check if the request // contains some data. request?.read(myBuffer) } responseHeaders = info?.allHeaders }Java
@Override public void onResponseStarted(UrlRequest request, UrlResponseInfo info) { int httpStatusCode = info.getHttpStatusCode(); if (httpStatusCode == 200) { // The request was fulfilled. Start reading the response. request.read(myBuffer); } else if (httpStatusCode == 503) { // The service is unavailable. You should still check if the request // contains some data. request.read(myBuffer); } responseHeaders = info.getAllHeaders(); }onReadCompleted()Cronet จะเรียกใช้เมธอดนี้เมื่อใดก็ตามที่มีการอ่านส่วนหนึ่งของเนื้อหาการตอบกลับ ตัวอย่างโค้ดต่อไปนี้แสดงวิธีใช้เมธอดและดึงข้อมูลเนื้อหาการตอบกลับ
Kotlin
override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) { // The response body is available, process byteBuffer. ... // Continue reading the response body by reusing the same buffer // until the response has been completed. byteBuffer?.clear() request?.read(myBuffer) }Java
@Override public void onReadCompleted(UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) { // The response body is available, process byteBuffer. ... // Continue reading the response body by reusing the same buffer // until the response has been completed. byteBuffer.clear(); request.read(myBuffer); }onSucceeded()Cronet จะเรียกใช้เมธอดนี้เมื่อคำขอเครือข่ายเสร็จสมบูรณ์ ตัวอย่างต่อไปนี้แสดงวิธีใช้เมธอด
Kotlin
override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) { // The request has completed successfully. }Java
@Override public void onSucceeded(UrlRequest request, UrlResponseInfo info) { // The request has completed successfully. }onFailed()Cronet จะเรียกใช้เมธอดนี้หากคำขอล้มเหลวไม่ว่าด้วยเหตุผลใดก็ตามหลังจากที่แอปเรียกใช้เมธอด
start()ตัวอย่างต่อไปนี้แสดงวิธีใช้เมธอดและรับข้อมูลเกี่ยวกับข้อผิดพลาดKotlin
override fun onFailed(request: UrlRequest?, info: UrlResponseInfo?, error: CronetException?) { // The request has failed. If possible, handle the error. Log.e(TAG, "The request failed.", error) }Java
@Override public void onFailed(UrlRequest request, UrlResponseInfo info, CronetException error) { // The request has failed. If possible, handle the error. Log.e(TAG, "The request failed.", error); }onCanceled()Cronet จะเรียกใช้เมธอดนี้หากคำขอถูกยกเลิกโดยใช้เมธอด
cancel()หลังจาก Cronet เรียกใช้onCanceled()แล้ว จะไม่เรียกใช้เมธอดอื่นๆ ของคลาสUrlRequest.Callbackคุณสามารถใช้วิธีนี้เพื่อเพิ่มทรัพยากรที่จัดสรรไว้เพื่อประมวลผลคำขอ ตัวอย่างต่อไปนี้แสดงวิธีใช้เมธอดKotlin
override fun onCanceled(request: UrlRequest?, info: UrlResponseInfo?) { // Free resources allocated to process this request. ... }Java
@Override public void onCanceled(UrlRequest request, UrlResponseInfo info) { // Free resources allocated to process this request. ... }