Retrofit is an encapsulation of the HTTP Web request framework, but Retrofit is only responsible for the encapsulation of the web interface, and the web request operation is actually done by OkHttp. Without further words, the food is served first, and the basic functionality is implemented. Implementation steps: 1. Add a dependency. Add retrofit dependencies under build.gradle in the project Demo:

Implementation ‘com. Squareup. Retrofit2: retrofit: 2.5.0’

The effect is as follows after the synchronization is completed:Gson is a Java object and JSON mutual conversion tool kit written by Google itself. It is lightweight, easy to use, and has a very complete document for inquiry. It is also an open source project. Since the server returned JSON data after I requested the access, I used gson to parse the returned data. I added gson dependencies under build.gradle in the Demo:

Implementation ‘com. Squareup. Retrofit2: converter – gson: 2.5.0’

The effect after adding equal synchronization is as follows:3. Create a JSON mapping to return data classes

The Json data format is:

{

“Success” : “Request successful”

}

So the constructed class is:

Public class Bean {/** ** Network request return format: */ @nonnull @override public String toString() {return "Success{" + Success + '}'; } private String Success; // private DemoBean demo; public Bean(String success) { this.Success = success; } public String getSuccess() { return Success; } public void setSuccess(String success) { this.Success = success; }}Copy the code

Override the toString() method inside, and output the returned data in the format of the override toString() method.

4. Create a Url constant class

Public class Constans {// Set default timeout time public static final int DEFAULT_TIME = 10; Public final static String BaseUrl = ""; Public final Static String retrofit = ""; public final static String retrofitList = ""; public final static String retrofitPost = ""; }Copy the code

The BaseUrl is the HTTP interface it needs to request, and the retroFIT and retrofitPost below are used for GET and POST requests, respectively.

5. Create an interface to describe network requests

Retrofit abstracts Http requests into Java interfaces, using annotations to describe and configure network request parameters. The interface is defined as follows:

Public interface ApiUrl {/** * valid link */ @get (constans.retrofit) // Call<Bean> getRetrofit(@query ("lightNum") String lightNum, @Query("lightStatus")String lightStatus); Call<Bean> getRetrofit(); @POST(Constans.retrofitPost) Call<Bean> postRetrofit(@Query("lightNum") String lightNum, @Query("lightStatus")String lightStatus); }Copy the code

The interface defines GET and POST requests, respectively.

6. Create an instance of Retrofit – create an instance in the MainActivity method:

Retrofit Retrofit = new retrofit.builder ().baseurl (constans.baseurl)// Set the Url of the network request AddConverterFactory (GsonConverterFactory. The create ()) / / set gson data parser. The build ();Copy the code

7. Start sending a request – Write the start sending request method in MainActivity. Here are examples of GET and POST requests, respectively:

GET request:

ApiUrl api = retrofit.create(ApiUrl.class); Call<Bean> demo = api.getretrofit (); Demo.enqueue (new Callback<Bean>() {Override public void onResponse(Call<Bean> Call, Log.e(TAG," request success message: "+ response.body().tostring ())); } @override public void onFailure(Call<Bean> Call, Throwable t) {log. d(TAG," request failure: " + t.getMessage()); // Failed message processing, output result}});Copy the code

POST request:

ApiUrl apiUrl = retrofit.create(ApiUrl.class); Call<Bean> demo = apiurl.postretrofit ("1","1"); Demo.enqueue (new Callback<Bean>() {Override public void onResponse(Call<Bean> Call, Log.e(TAG,"poet request success :" + response.body().tostring ()); // Request successful information processing, } @override public void onFailure(Call<Bean> Call, Throwable t) {log.d (TAG," request failure message :" + t.gettmessage ()); // Failed message processing, output result}});Copy the code

The complete GET and POST request code is as follows:

GET request:

Private void getRetrofit() {Retrofit Retrofit = new retrofit.builder ().baseurl (constans.baseurl)// Sets the Url of the network request AddConverterFactory (GsonConverterFactory. The create ()) / / set gson data parser. The build (); ApiUrl api = retrofit.create(ApiUrl.class); Call<Bean> demo = api.getretrofit (); Demo.enqueue (new Callback<Bean>() {Override public void onResponse(Call<Bean> Call, Log.e(TAG," request success message: "+ response.body().tostring ())); } @override public void onFailure(Call<Bean> Call, Throwable t) {log. d(TAG," request failure: " + t.getMessage()); // Failed message processing, output result}}); }Copy the code

POST request:

Private void postRetrofit() {Retrofit Retrofit = new retrofit.builder ().baseurl (constans.baseurl)// Sets the Url of the network request AddConverterFactory (GsonConverterFactory. The create ()) / / set gson data parser. The build (); ApiUrl apiUrl = retrofit.create(ApiUrl.class); Call<Bean> demo = apiurl.postretrofit ("1","1"); Demo.enqueue (new Callback<Bean>() {Override public void onResponse(Call<Bean> Call, Log.e(TAG,"poet request success :" + response.body().tostring ()); // Request successful information processing, } @override public void onFailure(Call<Bean> Call, Throwable t) {log.d (TAG," request failure message :" + t.gettmessage ()); // Failed message processing, output result}}); }Copy the code

8. Add permissions

Add network request permissions under Androidmanifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Copy the code

Android 9.0 will block HTTP requests

<application></application>    
Copy the code

Add the following property:

android:usesCleartextTraffic="true"
Copy the code

Completion of 9.

Finally, you can define two buttons in activity_main.xml, one click to implement the GET(getRetrofit method) request and the other click to implement the POST(postRetrofit method) request. The page layout is as follows:

The effect printed on the console is as follows: