Detailed tutorial on how to use Retrofit, and how to use retrofit
1. What is the fit framework?
It is a very popular network framework developed by Square, so we can see its name when importing its package. The current version is 2.
Features:
High performance, fast processing, and easy to use. Retrofit is one of the most popular HTTP Client libraries on Android.
Rest api design style
NIO (new I/o) supported)
By default, OKHttp is used to process network requests. I think it can be seen as an enhancement of OKHttp.
Gson resolution is used by default.
Go to the topic.
==========================================
2. How to use it? Step: 1. Import the package
Compile 'com. squareup. Invalid fit2: Invalid fit: 2.0.0-beta4'
After synchronization, the following will be added to External Libraries:
Retrofit-2.0.0-beta4
Okhttp-3.0.1
Okio-1.6.0
Compile 'com. squareup. Convert fit2: converter-gson: 2.0.0-beta4'
After synchronization, the following will be added to External Libraries:
Retrofit-2.0.0-beta4
Okhttp-3.0.1
Okio-1.6.0
Gson-2.4
Converter-gson-2.0.0-beta4
These packages are developed by Squareup.
Therefore, we only use compile 'com. squareup. Unzip fit2: converter-gson: 2.0.0-beta4.
2. Understand the frequently used annotation interfaces for network access in ipvfit2. In fact, these interfaces are under the packet of ipvfit2.http.
1. @ GET network Request Method
2. @ POST network Request Method
3. @ Headers () header information Parameters
4. @ Path () Path parameter, replace the content included in {} in the url
5. @ Query () Query parameters: append a string similar to "page = 1" to the url address to form the request parameters submitted to the server.
6. @ QueryMap
String of "type = text & username = abc & password = 123"
7. @ FormUrlEncoded encode the content entered in the form field to avoid garbled characters
8. @ Field () specifies the value and value of each space in the form Field.
9. @ FieldMap form field set
10. @ Multipart Post submits a Multipart request. If you upload a file, you must specify Multipart
11. @ Body Post: Submit a multipart request
3. Code steps:
1. Define an interface (encapsulate URL addresses and data requests)
2. instantiate Retrofit
3. Create an interface service object through the fit instance
4. interface service object Call methods in the interface to obtain the Call object
5. Call object execution requests (asynchronous and synchronous requests)
In the example:
{ "login": "basil2style", "id": 1285344, "avatar_url": "https://avatars.githubusercontent.com/u/1285344?v=3", "gravatar_id": "", "url": "https://api.github.com/users/basil2style", "html_url": "https://github.com/basil2style", "followers_url": "https://api.github.com/users/basil2style/followers", "following_url": "https://api.github.com/users/basil2style/following{/other_user}", "gists_url": "https://api.github.com/users/basil2style/gists{/gist_id}", "starred_url": "https://api.github.com/users/basil2style/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/basil2style/subscriptions", "organizations_url": "https://api.github.com/users/basil2style/orgs", "repos_url": "https://api.github.com/users/basil2style/repos", "events_url": "https://api.github.com/users/basil2style/events{/privacy}", "received_events_url": "https://api.github.com/users/basil2style/received_events", "type": "User", "site_admin": false, "name": "Basil", "company": "MakeInfo", "blog": "http://www.themakeinfo.com", "location": "Peterborough,ON,Canada", "email": "basiltalias92@gmail.com", "hireable": true, "bio": null, "public_repos": 45, "public_gists": 4, "followers": 52, "following": 145, "created_at": "2011-12-26T00:17:22Z", "updated_at": "2016-06-23T20:22:05Z"}
OK. Start to write the code according to the steps.
1. Define an interface (encapsulate URL addresses and data requests)
RequestServices. java
Package com. example. eventbus. using fittest; import okhttp3.ResponseBody; import using fit2.call; import using fit2.http. GET;/*** Created by LHD on 2016/6/25. */public interface RequestServices {// The Request Method is GET and the parameter is basil2style. Because there is no variable, the following getString method does not require the parameter @ GET ("basil2style ") // define the returned method. The returned response body uses the ResponseBody Call
GetString ();}
We usually put all the basic addresses in a class for convenient calling.
Constant. java
package com.example.eventbus.retrofittest;/** * Created by LHD on 2016/6/25. */public class Constant { //baseurl public final static String URL_BASE = "https://api.github.com/users/";}
2. instantiate Retrofit
// Obtain the fit object and set the address "fit = new fit. Builder (). baseUrl (Constant. URL_BASE). build ();
3. Create an interface service object through the fit instance
RequestServices requestServices = retrofit.create(RequestServices.class);
4. interface service object Call methods in the interface to obtain the Call object
Call
call = requestServices.getString();
5. Call object execution requests (asynchronous and synchronous requests)
Call. enqueue (new Callback
() {@ Override public void onResponse (Call
Call, Response
Response) {if (response. isSuccess () {try {Log. I ("LHD", response. body (). toString (); // The returned results are saved in response. string result = response in body. body (). string (); // The onResponse method runs in the main thread, that is, the UI thread, so we can directly update the UI textView here. setText (result);} catch (IOException e) {e. printStackTrace () ;}}@ Override public void onFailure (Call
Call, Throwable t) {Log. I ("LHD", "Access failed ");}});
All code:
MainActivity. java
Package com. example. eventbus. using fittest; import android. content. context; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. util. log; import android. widget. textView; import java. io. IOException; import okhttp3.ResponseBody; import response fit2.call; import response fit2.callback; import response fit2.response; import response fit2.0000fit; public class MainActivity extends AppCompatActivity {private Context mContext = this; private TextView textView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initView (); initemedifit ();} private void initView () {textView = (TextView) findViewById (R. id. TV _0000fit);} private void init0000fit () {// get the route fit object and set the URL to route fit = new route fit. builder (). baseUrl (Constant. URL_BASE ). build (); Log. I ("LHD", "1"); RequestServices requestServices = Dynamic Fit. create (RequestServices. class); Call
Call = requestServices. getString (); call. enqueue (new Callback
() {@ Override public void onResponse (Call
Call, Response
Response) {if (response. isSuccess () {try {Log. I ("LHD", response. body (). toString (); // The returned results are saved in response. string result = response in body. body (). string (); // The onResponse method runs in the main thread, that is, the UI thread, so we can directly update the UI textView here. setText (result);} catch (IOException e) {e. printStackTrace () ;}}@ Override public void onFailure (Call
Call, Throwable t) {Log. I ("LHD", "Access failed ");}});}}
Our code is to display the return value of the request on a textview. The final effect is as follows:
GET request syntax in fit2
1. GET request, with no parameters in the Method
@ GET ("article/page = 1") // not all Url addresses. This address and BaseUrl form a new address. Be careful when combining. Call
GetString (); // The method name is customized. Because there is no variable in the basic address, there is no parameter in our custom method, in fact, the parameter of this method is the parameter to be added to this address. // ResponseBody is the response body
2. GET request. The @ Path parameter and @ Query parameter are specified in the method.
@ Path is used to replace the contents of {And} in the url. @ Query adds a string similar to "page = 1" to the url address to form the request parameter submitted to the server @ GET (article/list/{type }?) Call
GetList (@ Path ('type') String type, @ Query ('page') int page );
3. GET request: submit the form data. Define the @ QueryMap parameter in the method.
The @ QueryMap parameter adds a string similar to "type = text & count = 30 & page = 1" to the url. @ GET ("MyWeb/RegServlet") Call
GetKey (@ QueryMap Map
Map );
4. GET request, with no parameters in the method. But define the complete Url path in @ URL. In this case, BaseUrl is ignored.
@GET("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2299165671,2554860548&fm=116&gp=0.jpg");Call
getData();
This is the simplest process of accessing the Alibaba fit network. The next article will provide a more in-depth explanation, including POST requests, obtaining network images, and using Gson to parse the returned json files.