2. RESTFUL Network Request Box Retrofit

Posted by WesPear on Sun, 31 Oct 2021 21:16:30 +0100

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

annotationExplain
@GETget request
@POSTpost request
@PUTput request
@DELETEdelete request
@PATCHpatch request, which complements the put request and updates local resources
@HEADhead Request
@OPTIONSoption request
@HTTPA 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

annotationExplain
@HeadersUsed 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
@HeaderA 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

NameExplain
@BodyUsed for post requests to send non-form data, such as when you want to post data in json format
@FiledUsed mostly for form fields in post requests, Filed and FieldMap require a combination of FormUrlEncoded
@FiledMapConsistent with @Filed for indeterminate form parameters
@PartFor form fields, Part and PartMap are used in conjunction with Multipart annotations for file uploads
@PartMapFor form fields, the default accepted type is Map, which can be used for multifile uploads
@PathPlaceholders for URLs
@QueryFor specifying parameters in Get
@QueryMapSimilar to Query
@UrlSpecify Request Path

1.4 Request and Response Format Comments

NameExplain
@FormUrlEncodedIndicates a request to send encoded form data, with @Field annotation required for each key-value pair
@MultipartIndicates a request to send multipart data requiring the use of @Part
@StreamingIndicates 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>
    
}

Topics: Java Android RESTful http