1. Concept
HttpClient | Removed in Android 6 (difficult to expand the number of APIs). |
HttpURLConnection | Currently officially integrated. |
OKHttp | Produced by Square, the realization of underlying communications. |
Retrofit | Produced by Square, the packaging of the upper-level interface makes it more convenient to use object-oriented thinking for network operations. |
2. Use
Android 9 has only allowed HTTPS-type network requests by default, and HTTP plaintext transmission is no longer supported due to security risks. If you insist on using it, you need to configure it: Right-click the res directory → New → Directory → Create an xml directory, Right-click the xml directory → New → File → Create a network_config.xml file, and the modification content is as follows:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config> </network-security-config>
Manifest {
//Add network access permissions
<uses-permission android:name="" />
//Allow HTTP access
<application
android:networkSecurityConfig="@xml/network_config"
</application>
}
2.1HttpURLConnection
thread { var connection: HttpURLConnection? = null try { val response = StringBuilder() val url = URL("") connection = () as HttpURLConnection = 8000 = 8000 //GET request val input = val reader = BufferedReader(InputStreamReader(input)) { (it) } print(()) //POST request = "POST" val output = DataOutputStream() ("username=admin&password=123456") } catch (e: Exception) { () } finally { connection?.disconnect() } }
2.2OKHttp
Portal
2.3Retrofit
View the latest version
implementation '.retrofit2:retrofit:2.9.0' //OkHttp and Okio will be downloaded together
implementation '.retrofit2:converter-gson:2.k6.1' //GSON will be downloaded together
2.3.1 Defining entity classes
Based on JSON content, write the corresponding entity class.
data class Person(var name: String, var age: Int)
2.3.2 Defining API Interface
According to the API interface, write the corresponding access file. Naming usually starts with a function name + ends with a service.
@GET | Get data from the server |
@POST | Submit data to the server |
@PUT @PATCH | Modify data on the server |
@DELETE | Delete data on the server |
interface PersonService { //Interface 1:/ @GET("") // means that the GET request is initiated, the address of the incoming request (relative path, repeated root path is configured later) fun getPerson(): Call<list<Person>> //The return value must be declared as the call type built in Retrofit, and the specific data type returned by the server is specified through generics //Interface 2:/<page>/ @GET("{page}/get_data.json") //Use {page} placeholder fun getData(@Path("page") page: Int): Call<Data> //Use the @Path("page") annotation to declare the corresponding parameters //Interface 3: /?u=<user>&t=<token> @GET("") fun getData(@Query("u") user: String, @Query("t") token: String): Call<Data> //Interface 4: /v2/place?query=Beijing&token={token}&lang=zh_CN @GET("v2/place?token=${}&lang=zh_CN") //The unchanged parameters are fixed in GET fun searchPlaces(@Query("query") query: String): Call<PlaceResponse> //Interface 5: /data/<id> @DELETE("data/{id}") fun deleteData(@Path("id") id: String): Call<ResponseBody> //This generic type can accept any type and will not be parsed //Interface 6: /data/create{"id": 1, "content": "The description for this data."} @POST("data/create") fun createData(@Body data: Data): Call<ResponseBody> //Convert the data in the Data object into JSON format text and put it in the body part of the HTTP request //Interface 7: /get_data.json // User-Agent: okhttp //header parameters are key-value pairs // Cache-Control: max-age=0 // Static declaration @Headers("User-Agent: okhttp", "Cache-Control: max-age=0") @GET("get_data.json") fun getData(): Call<Data> // Dynamic statement @GET("get_data.json") fun getData(@Header("User-Agent") userAgent: String, @Header("Cache-Control") cacheControl: String): Call<Data> }
2.3.3 Building Retrofit Objects
val retrofit = () .baseUrl("/") //Configure duplicate root path .addConverterFactory(()) //Specify the conversion library to use to parse the data (here is Gson) .build()
2.3.4 Create an API interface instance and call access functions
//Create a dynamic proxy objectval personService = (PersonService::) //Calling access function().enqueue(object : Call<List<person>> { //Can network request based on the address configured in the annotation override fun onResponse(call: Call<List<person>>, response: Response<List<person>>) { val list = () //Get parsed object } override fun onFailure(call: Call<List<person>>, t: Trouble) { () } })
2.3.5 Optimization
object GlobalRetrofit { private const val BASE_URL = "/" val retrofit: Retrofit = () .baseUrl(BASE_URL) .addConverterFactory(()) .build() //fun <T> create(serviceClass: Class<T>): T = (serviceClass) inline fun <reified T> create(): T = create(T::) } //useval personService = <PersonService>()
This is the article about the Retrofit usage tutorial on Android network access. For more related Android Retrofit content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!