Best fit practices and best fit practices
RetrofitIt is a RESTful Android (Java) client implementation. Based on annotations, it provides JSON to POJO (Plain Ordinary Java Object, simple Java Object), POJO to JSON, and network request (POST, GET, PUT, DELETE, and so on) Encapsulation encapsulates many details of Network calls. in the development process, we focus on object calls and do not care about the details of network requests, network Programming becomes simple. Is that the Code becomes more elegant and easy to read.
1. Package acquisition and installation
Maven Configuration
<dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.2.0</version></dependency>
Gradle Configuration
compile 'com.squareup.retrofit2:retrofit:2.2.0'
Directly apply the Jar package
2. Initialization
Create an interface and configure the annotation.
public interface APIClient { @GET("/api/movies") void movies(Callback<List<Movie>> callback);}
3. Configuration
Use the RestAdapter of Retrofit to generate a proxy class.
OkHttpClient client = new OkHttpClient(); mRestAdapter = new RestAdapter.Builder() .setEndpoint(baseUrl) .setClient(new OkClient(client)) .build(); myApiClient = mRestAdapter.create(APIClient.class);
Here, the client can specify its own configuration instance. Here I select OkClient, and you can also configure Other. The above configuration is the simplest configuration. Of course you can also configure some converters to convert the request Json string to an object.
4. Call
RetrofitdemoApplication.getInstance().myApiClient.movies(new Callback<List<Movie>>() { @Override public void success(List<Movie> moves, Response response) { mMovies=moves; mListView.setAdapter(new MovieAdapter(MovieActivity.this,moves)); Response r=response; } @Override public void failure(RetrofitError error) { String s=error.getMessage(); Toast.makeText(MovieActivity.this, "get data from API failuar", Toast.LENGTH_LONG).show(); } });
There are two methods for returning this call. One is the method for returning the failed method, and the other is the method for returning the failed method.