Retrofit is a high-quality and efficient HTTP request library. Retrofit relies on OkHttp internally. It encapsulates the underlying code and details of OKHttp and extends functions such as auto-parsing data model for returning results, switching of network engines, interceptors...
restFul is a web API interface that conforms to the rest architecture style and fully recognizes that Http is used to identify resources. restFul URL s are resource-oriented and uniquely identify and locate resources. What to do with the resource identified by the URL is determined by the Http method.
There are four rest ing request methods, including get,post,put,delete.
Author: Head forward in search of myself
Links: https://www.jianshu.com/p/dfe3077ddbcd
Source: Short Book
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.
1. Notes
retrofit Annotation Driven Upper Network Request Framework, which uses annotations to simplify requests, is generally divided into the following categories:
- Notes for labeling network requests
- Comments marking network request parameters
- Comments to mark network request and response formats
Pictures and some text from https://www.songyubao.com/book/primary/network/Retrofit.html
1.1 Request Method Comments
annotation | Explain |
---|---|
@GET | get request |
@POST | post request |
@PUT | put request |
@DELETE | delete request |
@PATCH | patch request, which complements the put request and updates local resources |
@HEAD | head Request |
@OPTIONS | option request |
@HTTP | A generic annotation that replaces all the above annotations has three properties: method, path, hasBody |
1.2 Request Header Comments
It can be marked either in a method or in a parameter
annotation | Explain |
---|---|
@Headers | Used to add fixed request headers, you can add multiple at the same time. Request headers added through this comment do not override each other but coexist |
@Header | A parameter passed in as a method to add a Header with an unfixed value that updates an existing request Header |
1.3 Request parameter comments
Name | Explain |
---|---|
@Body | Used for post requests to send non-form data, such as when you want to post data in json format |
@Filed | Used mostly for form fields in post requests, Filed and FieldMap require a combination of FormUrlEncoded |
@FiledMap | Consistent with @Filed for indeterminate form parameters |
@Part | For form fields, Part and PartMap are used in conjunction with Multipart annotations for file uploads |
@PartMap | For form fields, the default accepted type is Map, which can be used for multifile uploads |
@Path | Placeholders for URLs |
@Query | For specifying parameters in Get |
@QueryMap | Similar to Query |
@Url | Specify Request Path |
1.4 Request and Response Format Comments
Name | Explain |
---|---|
@FormUrlEncoded | Indicates a request to send encoded form data, with @Field annotation required for each key-value pair |
@Multipart | Indicates a request to send multipart data requiring the use of @Part |
@Streaming | Indicates that the response is returned as a byte stream. If this annotation is not used, it will load all the data into memory by default. This annotation is particularly useful for downloading large files |
2 Start using
step1: add dependencies
app/build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' //json transformation
step2: Initialization
object FirstRetrofit { //OkHttpClient object private val okClient:OkHttpClient = OkHttpClient.Builder() //builder Builder Design Pattern .connectTimeout(10,TimeUnit.SECONDS) //Connection timeout .readTimeout(10,TimeUnit.SECONDS) //Read Timeout .writeTimeout(10,TimeUnit.SECONDS) //Write Timeout .addInterceptor(LoggingInterceptor()) //Interceptor .build() //Initialization private val retrofit:Retrofit = Retrofit.Builder() .client(okClient) //Object to configure OkHttp network request framework .baseUrl("http://123.56.232.18:8080/serverdemo/")//Domain name of network request .addConverterFactory(GsonConverterFactory.create()) //Data Conversion Adapter .build() //Initiate a network request //Public <T> T create (final Class <T> service) Java type fun <T> create(clazz: Class<T>):T{ return retrofit.create(clazz) } } //Network Request Interface interface ApiService{ //encoded by @Query initiates a network request to avoid encoding the interface (to prevent Chinese scrambling) //@Query (value = userId, encoded = true) is used to decorate userId:String @GET(value = "user/query") fun queryUser(@Query(value = "userId", encoded = true) userId:String):Call<UserResponse> }
step3:Call
enqueue() is used asynchronously and execute() is used synchronously.
val apiService = FirstRetrofit.create(ApiService::class.java) apiService.queryUser("1600933269").enqueue(object :Callback<UserResponse>{ override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) { Log.e("Retrofit",response.body()?.toString()?:"response is null") } override fun onFailure(call: Call<UserResponse>, t: Throwable) { Log.e("Retrofit",t.message?:"unknown reason") } })
Tips:
Both onResponse and onFailure callbacks are in the main thread
UI controls can be manipulated directly
Request Method Definition
//Network Request Interface interface ApiService{ //encoded by @Query initiates a network request to avoid encoding the interface (to prevent Chinese scrambling) //@Query (value = userId, encoded = true) is used to decorate userId:String @GET(value = "user/query") fun queryUser(@Query(value = "userId", encoded = true) userId:String):Call<UserResponse> //Add multiple request headers using @Headers @Headers("User-Agent:android", "apikey:123456789") @GET(value = "user/query") fun queryUser1(@Query(value = "userId" , encoded = true) userId: String):Call<UserResponse> //@QueryMap can be used with multiple parameters, but only on GET requests @GET(value = "user/query") fun queryUser2(@QueryMap(encoded = true) queryMap: Map<String?, String?>):Call<UserResponse> /** * In many cases, we need to upload data in json format. When we register new users, there is a relatively large amount of data when they register. * It may change in the future, at which point the server may ask us to upload data in json format. This is done with the @Body annotation. * Directly into the entity, which will itself be converted to Json, @Body can only be used on POST requests * * String Commit */ @POST("user/update") fun userUpdate(@Body post: User):Call<UserResponse> /** * Form submission (key-value pair submission) * Used mostly for form fields in post requests, Filed and FieldMap require a combination of FormUrlEncoded */ @POST() @FormUrlEncoded fun executePost(@FieldMap map:Map<String , User>):Call<UserResponse> /** * Form upload file (key-value pair submission, file upload at the same time) */ @Multipart @FormUrlEncoded @POST("upload/upload") fun register( @Field("openId") openId:String, @PartMap map:Map<String? , MultipartBody.Part> ):Call<UserResponse> }