Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Retrofit

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to use Retrofit". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use Retrofit" can help you solve the problem.

Retrofit

All the Retrofit in the article refers to Retrofit2.

Retrofit can actually be understood as an enhanced version of OkHttp, which is also a network loading framework. The underlying layer is encapsulated using OKHttp. To be exact, the job of a network request is essentially done by OkHttp.

Retrofit is only responsible for the encapsulation of the network request interface. One of its features is that it contains a lot of notes.

Easy to simplify the amount of your code.

Advantages:

Super decoupling

Different HttpClient can be configured to implement network requests.

Support for synchronous, asynchronous and RxJava

You can configure different deserialization tools to parse data, such as json, xml

The request speed is fast and the use is very convenient and flexible.

Retrofit usage

Configuration dependencies:

Implementation 'com.squareup.retrofit2:retrofit:2.5.0'//Retrofit dependencies implementation' com.squareup.retrofit2:converter-gson:2.5.0'// optional dependencies used to parse json characters

_

Network permissions:

_

Steps:

Define interface classes (encapsulate URL addresses and data requests)

Instantiate Retrofit

Create interface service object through Retrofit instance

The interface service object calls the method in the interface to get the Call object

Call object executes requests (asynchronous, synchronous requests)

Create a Retrofit instance

Retrofit retrofit = new Retrofit.Builder () .baseUrl ("http://localhost:6666") .build ()

_

Get request / / baseURL (from the beginning to the end of any slash) String baseURL= "https://www.wanandroid.com/article/list/0/";@GET("json?cid=60")Call getData (); / / get the Retrofit object Retrofit retrofit = new Retrofit.Builder () .baseUrl (MyServer.baseURL) .build (); / / get the interface service object MyServer server = retrofit.create (MyServer.class) through Retrofit / / the interface object calls its method to get the call object Call data = server.getData (); / / it is similar to the okhttp method, except that the android system callback method executes the request data.enqueue (new Callback () {@ Override public void onResponse (Call call, Response response) {try {String json = response.body (). String ()) in the main thread / / call. Log.e (TAG, "onFailure:" + response.body (). String ());} catch (Exception e) {e.printStackTrace ();} @ Override public void onFailure (Call call, Throwable t) {Log.e (TAG, "onFailure:" + t.getMessage ());}})

_

Post request String URL = "http://apicloud.mob.com/appstore/health/";// must end with a backslash public interface MyServer {/ / POST (" search? ") POST ("search") same / / @ Field ("key") String value post request for parameter submission / / @ FormUrlEncoded post request when submitting a form form, you need to add this annotation to encode the submitted parameters / / post request do not submit parameters, do not add, / / if there are submitted parameters, do not add @ FormUrlEncoded / / @ Field and @ FieldMap @ FieldMap simply combines one parameter by one into a map @ POST ("search?") @ FormUrlEncoded Call postData1 (@ Field ("key") String appKey,@Field ("name") String appKey) @ POST ("search") @ FormUrlEncoded Call postData2 (@ FieldMap Map map);} / / POST Asynchronous private void initPostEnqueue () {/ / 1. Create the Retrofit object Retrofit retrofit = new Retrofit.Builder (). BaseUrl (MyServer.URL). Build (); / / 2. Get the MyServer interface service object MyServer myServer = retrofit.create (MyServer.class); / / 3. Get the Call object / / method-Call call1 = myServer.postData1 ("908ca46881994ffaa6ca20b31755b675"); / / Mode 2 / / there is no need to switch the main thread, because Retrofit helps us cut through / / okHttpClient needs to switch the main thread Map map = new HashMap (); map.put ("appKey", "908ca46881994ffaa6ca20b31755b675"); Call call = myServer.postData2 (map) / / 4.Call object execution request call.enqueue (new Callback () {@ Override public void onResponse (Call call,Response response) {try {String result = response.body () .string (); Log.e ("retrofit", "onResponse:" + result); tv.setText (result) / / by default, the main thread} catch (IOException e) {e.printStackTrace ();} @ Override public void onFailure (Call call, Throwable t) {Log.e ("retrofit", "onFailure:" + t.getMessage ());}});});}

_

Notes on Retrofit

/ / get@GET ("data/%E7%A6%8F%E5%88%A9/20/2") Call getData (); / / post@POST ("data/%E7%A6%8F%E5%88%A9/20/2") Call getData2 () / / field@POST ("register") @ FormUrlEncodedCall getData3 (@ Field ("username") String username, @ Field ("password") String password, @ Field ("phone") String phone, @ Field ("verify") String verify); / / query@GET ("project/list/1/json") Call getData4 (@ Query ("cid") int cid) / / fieldMap@POST ("register") @ FormUrlEncodedCall getData5 (@ FieldMap Map map); / queryMap@GET ("project/list/1/json?") Call getData6 (@ QueryMap Map map); / / body@POST ("user/login") Call getData7 (@ Body RequestBody requestBody); / / path@GET ("data/%E7%A6%8F%E5%88%A9/20/ {page}") Call getData8 (@ Path ("page") int page); / / url@GETCall getData9 (@ Url String url_query)

_

Set up headers

Method 1:

This is a common way to add a single headers and multiple headers

Mode 2:

Code addition

Mode 3:

Data parsing (Converter)

Retrofit supports multiple ways of data parsing.

Need to add dependencies in Geadle

Gson:implementation 'com.squareup.retrofit2:converter-gson:2.0.2'Jackson:implementation' com.squareup.retrofit2:converter-jackson:2.0.2'

Contrast Okhttp

To be exact, Retrofit is an encapsulation of RESTful's HTTP network request framework.

Reason: the work of the network request is essentially done by OkHttp, while Retrofit is only responsible for the encapsulation of the network request interface

The App application requests the network through Retrofit. In fact, the Retrofit interface layer is used to encapsulate the request parameters, Header, Url and other information, and then OkHttp completes the subsequent request operations.

After the data is returned from the server, OkHttp sends the original result to Retrofit,Retrofit to parse the result according to the user's needs.

Hook

Because his lower layer is okhttp, the same set of hook okhttp can be hook Retrofit.

This is the end of the introduction to "how to use Retrofit". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report