OkHttp is an open source HTTP client library for making network requests and handling responses in Java and Kotlin applications. Developed by Square, it provides a simple, efficient and easy-to-use API.
- Supports HTTP/2 and SPDY: OkHttp supports the latest HTTP protocol versions, including HTTP/2 and SPDY, to provide faster and more efficient network communication.
- Connection pool and request reuse: OkHttp automatically manages the connection pool, reuses existing connections, and reduces the delay and resource consumption of network requests.
- Request and response interceptors: OkHttp provides an interceptor mechanism that can intercept and modify the process of sending requests and receiving responses. This makes it very easy to add custom headers, authentication, logging, and more.
- Response caching: OkHttp supports response caching, which can reduce network requests and improve application performance and response speed.
- WebSocket support: OkHttp has built-in support for the WebSocket protocol, making it easy to establish and manage WebSocket connections for real-time communication.
- Security support: OkHttp provides TLS and SSL support, including certificate verification and certificate pinning functions to ensure the security of network communications.
- Asynchronous requests and callbacks: OkHttp supports asynchronous requests and callback mechanisms. You can send requests in the background thread and get the corresponding callback results after the request is completed. The usage is as follows
network request
<uses-permission android:name="android.permission.INTERNET"/>
Dependent libraries
//define a BOM and its version implementation(platform("com.squareup.okhttp3:okhttp-bom:4.11.0")) // define any required OkHttp artifacts without version implementation("com.squareup.okhttp3:okhttp") implementation("com.squareup.okhttp3:logging-interceptor")
1. GET
1.get synchronization request
Synchronous requests should not be made on the main thread
val client=OkHttpClient() fun get(){<!-- -->//Network request body Thread(Runnable {<!-- --> //Construct the request body val request:Request=Request.Builder() .url(BASE_URL) .build() //Construct the request object val call:Call= client.newCall(request) //Initiate a synchronous request execute--synchronous execution val response:Response=call.execute() val body:String ?=response.body?.string() Log.v("mainokk","$body") }).start() }
2. get remote request
val client=OkHttpClient() fun getAsync(){<!-- -->//Network request body val request:Request=Request.Builder() .url(BASE_URL) .build() //Construct the request object val call:Call= client.newCall(request) //Initiate a synchronous request execute--synchronous execution call.enqueue(object :Callback{<!-- --> override fun onFailure(call: Call, e: IOException) {<!-- --> TODO("Not yet implemented") } override fun onResponse(call: Call, response: Response) {<!-- --> val body:String ?=response.body?.string() Log.v("mainokk","$response") } }) }
The steps of asynchronous requests are similar to synchronous requests, except that the call’s enquene method is used to make asynchronous requests, and the results are processed through the callback’s onResponse method and onFailure method.
The basic process is to first create an okHttpClient object, and then create a Request object through Request.Builder(). The OkHttpClient object calls newCall() and passes in the Request object to obtain a call object.
The difference lies in the calls to execute() and enquene() methods. Calling execute() is a synchronous request and returns a Response object.
Call the enquene() method to test and return the Response object in the form of callback
2. POST
The difference between POST request and GET request is Request. Builder’s post() method, the post() method requires a RequestBody object as a parameter
1. post synchronous request (form submission)
val client=OkHttpClient() fun post(){<!-- --> Thread(Runnable{<!-- --> val body:FormBody=FormBody.Builder() .add("","") .build() val request =Request.Builder().url(BASE_URL) .post(body) .build() val call:Call= client.newCall(request) val response:Response=call.execute() Log.v("mainokk","$response") }) }
2. post asynchronous request (form submission)
val client=OkHttpClient() fun postAsync(){<!-- -->//Network request body val body:FormBody=FormBody.Builder() .add("","") .build() val request:Request=Request.Builder() .url(BASE_URL) .post(body) .build() val call:Call= client.newCall(request) call.enqueue(object :Callback{<!-- --> override fun onFailure(call: Call, e: IOException) {<!-- --> TODO("Not yet implemented") } override fun onResponse(call: Call, response: Response) {<!-- --> val body:String ?=response.body?.string() Log.v("mainokk","${response.body?.string()}") } }) }
3. Interceptor LoggingInterceptor
The interceptor is a relatively powerful mechanism in OkHttp, which can monitor, rewrite and retry calling requests.
This is a relatively simple implementation of Interceptor, which outputs some information about request sending and response.
class loggingInterceptor:Interceptor {<!-- --> override fun intercept(chain: Interceptor.Chain): Response {<!-- --> val time_start:Long=System.nanoTime() val request=chain.request() val response=chain.proceed(request) val buffer= Buffer() request.body?.writeTo(buffer) val resquestBodyStr:String=buffer.readUtf8() Log.e("OKHTTP",String.format("")) val bussinessData=response.body?.string()?:"response" val mediaType=response.body?.contentType() val newBody=ResponseBody.create(mediaType,bussinessData) val newResponse=response.newBuilder().body(newBody).build() val time_end:Long=System.nanoTime() Log.e("OKHTTP",String.format("")) return newResponse } }
use
val client=OkHttpClient.Builder() .addInterceptor(loggingInterceptor()) .build()
The following are five important interceptors in OkHttp:
- RetryInterceptor (retry interceptor): When the request fails, RetryInterceptor will automatically retry the request. It can control retry behavior by setting the maximum number of retries and the retry interval.
- CacheInterceptor (cache interceptor): CacheInterceptor checks whether a cached response is available and returns a cached response when there is no network connection. It also updates the cache to ensure data consistency.
- ConnectInterceptor (connection interceptor): ConnectInterceptor is responsible for establishing a connection with the server. It handles operations such as TLS handshakes, HTTP proxies, and redirects.
- CallServerInterceptor (call server interceptor): CallServerInterceptor is responsible for sending requests to the server and receiving responses. It also handles operations such as redirection, compression, and authentication.
- BridgeInterceptor (Bridge Interceptor): BridgeInterceptor is responsible for converting user requests into network requests and converting server responses into user responses. It also handles operations such as request headers, response headers, and request bodies.
These interceptors can be combined in a certain order to implement different functions and logic
Finally
If you want to become an architect or want to break through the 20-30K salary range, then don’t be limited to coding and business, you must be able to select and expand, and improve your programming thinking. In addition, good career planning is also very important, and learning habits are important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.
If you have no direction, here is a set of “Advanced Notes on the Eight Major Modules of Android” written by a senior architect at Alibaba to help you systematically organize messy, scattered, and fragmented knowledge, so that you can systematically and efficiently Master various knowledge points of Android development.
Compared with the fragmented content we usually read, the knowledge points in this note are more systematic, easier to understand and remember, and are strictly arranged according to the knowledge system.
Everyone is welcome to support with one click and three links. If you need the information in the article, just scan the CSDN official certification WeChat card at the end of the article to get it for free ↓↓↓ (There is also a small bonus of the ChatGPT robot at the end of the article, don’t miss it)