Development fit for Android Network Framework Learning

Source: Internet
Author: User

Development fit for Android Network Framework Learning
Overview: in the previous article, we compared Volley, Retrofit, and OKHttp.Option: You can use Retrofit for the AndroidHTTP request library, and Android-Universal-Image-Loader (or Picasso) for images. If Retrofit does not meet your requirements, use okhttp. In general, the first two have been able to solve most of the problems, and they are much easier to use than Volley.Learn to use Retrofit, OKHttp, and GSON in sequence
Retrofit: A type-safe REST client for Android and JavaRetrofit simplifies data downloading from Web APIs and parses data into common Java objects (POJO ). For example, to download the user repository information from Github, you only need to write the following lines:

@GET("/users/{user}/repos")List listRepos(@Path("user") String user);
OkHttp:OKHttp is an Http client for Android. Very efficient. Supports SPDY, connection pool, GZIP, and HTTP cache. By default, OKHttp automatically handles common network problems, such as secondary connections and SSL handshakes. If your application integrates OKHttp, ingress fit uses OKHttp by default to process requests from other network layers.. Gson:GSON is a Java library that parses JSON into POJO. GSON can also parse POJO into JSON. Retrofit uses GSON to parse JSON data.Use jsonschema2pojo to create POJO1. Use the website composer-a GSON-t json -- source jsonaddress -- target java-gen.
Alibaba fit Official Website: http://square.github.io/retrofit/

1) POJO or model entity class: JSON data obtained from the server will be filled into this type of instance.
2) interface: we need to create an interface to manage the URLs of requests such as GET, POST.... This is a service class.
3) RestAdapter class: This is a RestClient class. By default, Gson is used to parse JSON data in retrofit. You can also set your own JSON parser, such as jackson.

Installation:

Maven method:
<dependency>  <groupId>com.squareup.retrofit</groupId>  <artifactId>retrofit</artifactId>  <version>1.9.0</version></dependency>
Gradle mode:
compile 'com.squareup.retrofit:retrofit:1.9.0'
Transform RestAPI into a java interface using Retrofit:
public interface GitHubService {  @GET("/users/{user}/repos")  List<Repo> listRepos(@Path("user") String user);}
RestAdapter creates an HTTP connection and is used to create GitHubService:
RestAdapter restAdapter = new RestAdapter.Builder()    .setEndpoint("https://api.github.com")    .build();GitHubService service = restAdapter.create(GitHubService.class);
Each time you call a method in GitHubService, an HTTP request is created to the server:
List<Repo> repos = service.listRepos("octocat");
The preceding annotations describe the benefits of HTTP requests:
  • URL parameter replacement and query parameter support
  • Object conversion to request body (e.g., JSON, protocol buffers)
  • Multipart request body and file upload
API annotation all requests require a request method annotation and use the relative URL path as the parameter. Five annotations are built in: GET, POST, PUT, DELETE, and HEAD.
@ GET ("/users/list ")
You can also specify the query parameter @ GET ("/users/list? Sort = desc ")
The URL operation can dynamically change all request URLs in the following form:
@GET("/group/{id}/users")List<User> groupList(@Path("id") int groupId);
The parameter is modified with the @ Path annotation. @ Path ("id") corresponds to {id}. You can also add the Query in this form: @ Query
@GET("/group/{id}/users")List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);
You can use map to add more complex queries:
@GET("/group/{id}/users")List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
REQUEST BODY
@POST("/users/new")void createUser(@Body User user, Callback<User> cb);
Note that using a POJO as the request body will be converted by RestAdapter. In the POST mode, callback can be passed in. Form encoded and multipart form fields AND file upload @ FormUrlEncoded modify FORM fields. Each FORM Field sub-component key-value is modified by @ Field.
@FormUrlEncoded@POST("/user/edit")User updateUser(@Field("first_name") String first, @Field("last_name") String last);
@ Multipart modifier is used for file upload. Each Part element is modified with @ Part:
@Multipart@PUT("/user/photo")User updateUser(@Part("photo") TypedFile photo, @Part("description") TypedString description);
Processing Header:
@Headers("Cache-Control: max-age=640000")@GET("/widget/list")List<Widget> widgetList();
@Headers({    "Accept: application/vnd.github.v3.full+json",    "User-Agent: Retrofit-Sample-App"})@GET("/users/{username}")User getUser(@Path("username") String username);
@GET("/user")void getUser(@Header("Authorization") String authorization, Callback<User> callback)
If you want to add the same Header to all requests You can use the RequestIntercepor format:
RequestInterceptor requestInterceptor = new RequestInterceptor() {  @Override  public void intercept(RequestFacade request) {    request.addHeader("User-Agent", "Retrofit-Sample-App");  }};RestAdapter restAdapter = new RestAdapter.Builder()  .setEndpoint("https://api.github.com")  .setRequestInterceptor(requestInterceptor)  .build();
Synchronous, asynchronous, and the following methods can be observed: A method with a return type will be executed synchronously.
@GET("/user/{id}/photo")Photo getUserPhoto(@Path("id") int id);
Asynchronous execution requires the last parameter of the method be a Callback.
@GET("/user/{id}/photo")void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
However, in Android, Callback is called and executed in the main thread.In short, the form with the return value is synchronous, and the form with the Callback parameter is asynchronous request. Return observation:
@GET("/user/{id}/photo")Observable<Photo> getUserPhoto(@Path("id") int id);
Observable requests are subscribed asynchronously and observed on the same thread that executed the HTTP request. to observe on a different thread (e.g. android's main thread) call observeOn (schedeon) on the returned Observable.
RESPONSE OBJECT TYPE Note: RestAdapter completes the conversion of all JSON and Object types in Retrofit.
@GET("/users/list")List<User> userList();@GET("/users/list")void userList(Callback<List<User>> cb);@GET("/users/list")Observable<List<User>> userList();
If you want to access the original HTTP response:
@GET("/users/list")Response userList();@GET("/users/list")void userList(Callback<Response> cb);@GET("/users/list")Observable<Response> userList();
RestAdaper configuration JSON conversion: Container fit uses Gson by default. If you want to customize Gson conversion (e.g. naming policies, date formats, custom types), you can provide a Gson object during RestAdapter construction.
Gson gson = new GsonBuilder()    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)    .registerTypeAdapter(Date.class, new DateTypeAdapter())    .create();RestAdapter restAdapter = new RestAdapter.Builder()    .setEndpoint("https://api.github.com")    .setConverter(new GsonConverter(gson))    .build();GitHubService service = restAdapter.create(GitHubService.class);
Process XML Conversion:
RestAdapter restAdapter = new RestAdapter.Builder()    .setEndpoint("https://api.soundcloud.com")    .setConverter(new SimpleXMLConverter())    .build();SoundCloudService service = restAdapter.create(SoundCloudService.class);
Error Handling
class MyErrorHandler implements ErrorHandler {  @Override public Throwable handleError(RetrofitError cause) {    Response r = cause.getResponse();    if (r != null && r.getStatus() == 401) {      return new UnauthorizedException(cause);    }    return cause;  }}RestAdapter restAdapter = new RestAdapter.Builder()    .setEndpoint("https://api.github.com")    .setErrorHandler(new MyErrorHandler())    .build();
Log processing:
RestAdapter restAdapter = new RestAdapter.Builder()    .setLogLevel(RestAdapter.LogLevel.FULL)    .setEndpoint("https://api.github.com")    .build();
When okHttpRetrofit is integrated, once okHttp is found in the project, okHttp is automatically integrated. Proguard:
-dontwarn retrofit.**-keep class retrofit.** { *; }-keepattributes Signature-keepattributes Exceptions

Refer:Http://stackoverflow.com/questions/27960801/should-i-use-okhttp-with-volley-library
Http://stackoverflow.com/questions/16902716/comparison-of-android-networking-libraries-okhttp-retrofit-volley/
Http://blog.jobbole.com/65170/
Https://www.v2ex.com/t/180575
Https://github.com/bboyfeiyu/android-tech-frontier/tree/master/issue-7/Retrofit%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97
Http://www.cnblogs.com/ct2011/p/3997368.html? Utm_source = tuicool

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.