Because the resources found on the Internet are not just some strings or some binary numbers, but also some pictures that can be seen with the naked eye, so how do we display a picture on the component when we send a network request?
This is to use a property (byteStream) of the result returned by the okhttp request:
var input = result.byteStream() bitmap=BitmapFactory.decodeStream(input) myhanlder.sendEmptyMessage(3)
Combined with the previously learned method of sending get asynchronous requests through okhttp, you can write such code:
OkhttpUtils.get().doGet(url,object :NetWorkCallBack{ override fun onSuccess(result: ResponseBody) { //TODO("Not yet implemented") var input = result.byteStream() bitmap=BitmapFactory.decodeStream(input) myhanlder.sendEmptyMessage(3) } override fun onFail(msg: String) { //TODO("Not yet implemented") Toast.makeText(this@Okhttp,"Request failed",Toast.LENGTH_SHORT).show() } })
OkhttpUtils here is an encapsulated class, so there are only two result status functions (onSuccess and onFail):
1. Encapsulation of the request
When I used this framework before, I used a lot of methods, including get, json, and forms, and now there is a picture download, so I just said that these request methods are encapsulated in a tool class, which is written like this :
package com.example.hanlderpractice.service import com.example.hanlderpractice.entity.NetWorkCallBack import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import org.json.JSONObject import java.io.IOException import java.util.concurrent.TimeUnit class OkhttpUtils public constructor() { companion object { private var instance: OkhttpUtils? = null get() { if (field == null) { field = OkhttpUtils() } return field } fun get(): OkhttpUtils { return instance!! } } private var client:OkHttpClient?=null init { client=OkHttpClient.Builder() .readTimeout(5,TimeUnit.SECONDS) .connectTimeout(5,TimeUnit.SECONDS) .build() } fun doGet(url:String,netWorkCallBack: NetWorkCallBack):Unit{ var request=Request.Builder() .url(url) .build() client?.newCall(request)?.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { //TODO("Not yet implemented") netWorkCallBack.onFail("Request failed") } override fun onResponse(call: Call, response: Response) { //TODO("Not yet implemented") netWorkCallBack.onSuccess(response.body!!) } }) } fun doJson(url:String,jsonobject:JSONObject,netWorkCallBack: NetWorkCallBack):Unit{ var jsonstr=jsonobject.toString().toRequestBody("application/json;charset=utf-8".toMediaType()) var request: Request=Request.Builder() .url(url) .post(jsonstr) .build() client?.newCall(request)?.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { //TODO("Not yet implemented") netWorkCallBack.onFail("Request failed") } override fun onResponse(call: Call, response: Response) { //TODO("Not yet implemented") netWorkCallBack.onSuccess(response.body!!) } }) } fun doForm(url:String,formBody:FormBody,netWorkCallBack: NetWorkCallBack):Unit{ var request: Request=Request.Builder() .url(url) .post(formBody) .build() client?.newCall(request)?.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { //TODO("Not yet implemented") netWorkCallBack.onFail("Request failed") } override fun onResponse(call: Call, response: Response) { //TODO("Not yet implemented") netWorkCallBack.onSuccess(response.body!!) } }) } }
Rewrite the get method of this tool class by deriving objects so that it can only be instantiated once, which is a common singleton pattern;
Another object is the interface used to store the requested data, so these two return result status functions are in this interface:
package com.example.hanlderpractice.entity import okhttp3.ResponseBody interface NetWorkCallBack { public fun onSuccess(result:ResponseBody) public fun onFail(msg:String) }
This is an interface. After I call the method of sending the request, I will get a request result object, so I will throw the result (the data requested by the tool class) in this interface, and I can use it elsewhere (The class that calls the request method of the tool class) got:
var url="http://119.img.pp.sohu.com/images/blog/2007/9/28/18/15/115e6595d75.jpg" OkhttpUtils.get().doGet(url,object :NetWorkCallBack{ override fun onSuccess(result: ResponseBody) { //TODO("Not yet implemented") var input = result.byteStream() bitmap=BitmapFactory.decodeStream(input) myhanlder.sendEmptyMessage(3) }
For example, here, the doGEt method in the tool class is used here, and the second parameter is this interface. The parameter in its success function is the requested data body. At this time, directly create its byte stream and convert it into a bitmap The object can be displayed on the imageview component. Of course, if you don’t send a lot of requests, you can also send the get request directly without encapsulation. Here is the same effect. When you get the byte stream of the data body, you can convert it. It is a bitmap object;
Other post form requests can return the data body through this interface in the same way;
2. Set the picture
//Create a weak reference handler private class MyHanlder(var wk: WeakReference<Okhttp>): Handler(Looper.getMainLooper()){ override fun handleMessage(msg: Message) { super.handleMessage(msg) wk.get()?.run { if(msg.what==1){ Toast.makeText(this,"login successful", Toast.LENGTH_SHORT).show() var intent: Intent = Intent(this,MainActivity::class.java) startActivity(intent) }else if(msg.what==2){ } else if(msg.what==3){ iv_header.setImageBitmap(bitmap); }else{ Toast.makeText(this,"Login failed", Toast.LENGTH_SHORT).show() } } } }
Similarly, sending requests can only be in sub-threads, while updating the interface needs to send messages, here is the message when what=3, so set this bitmap constructed from network data to the component;
No matter which picture it is, here is a sample, or it can be other photos, which can be displayed on the component in the same way;