"Android Combat"----from retrofit source analysis to the Java Network Programming and HTTP authoritative guide to think of

Source: Internet
Author: User

First, Introduction

Connected to an "Android combat"----based on retrofit implementation of multi-image/file, text upload has said very much want to understand why retrofit so dick. Recently also read some of its source code analysis of the article and personally view the source code, found that the Java Network Programming and HTTP authoritative guidelines have a good interpretation. All along, have embraced a principle, in this new technology in the changing times, how to base in the Java world, with the two points:

1, basic skills, including: Java basic knowledge, (Java programming ideas, effective Java), Java Advanced (Java Virtual machine, Java design mode), network-related (this era no network is not everything, Java network programming, HTTP authoritative guide, tcp/ IP protocol), computer system-related (in-depth understanding of computer systems) These are all fundamental, so-called original aim, in mastering these basic skills, and then learn new technologies, in the face of the ever-changing new technology will be at ease.

2, the ability to concatenate trivial knowledge, that is, to summarize the ability. Whether in the work or study, the first use of knowledge is a piece of East, west, in fact, many things are related, through the systematic comb to form their own knowledge system, to create their own exclusive domain, which is also in the Java community based on the fundamental.

These are purely their own this time of the blind think nonsense, we encourage each other.

Ii. Introduction of Retrofit

See Jake Wharton's Speech https://realm.io/cn/news/droidcon-jake-wharton-simple-http-retrofit-2/

Retrofit was developed by the Square company. Square has launched many excellent Android open source projects on GitHub. For example: Otto (Event bus), leakcanary (troubleshooting memory leaks), Android-times-square (Calendar control), dagger (Dependency injection), Picasso (loading pictures asynchronously), okhttp (network request), retrofit (Network request) and so on. More open-source projects on square we can go to the square's GitHub for viewing.

According to Retrofit's official documentation (HTTPS://GITHUB.COM/SQUARE/RETROFIT and http://square.github.io/retrofit/) retrofit is

A type-safe HTTP Client for Android and Java


Visible retrofit can be applied to the Android platform and Java platform, its source code can also be seen Retrofit2\platform.java

private static Platform Findplatform () {    try {      class.forname ("Android.os.Build");      if (Build.VERSION.SDK_INT! = 0) {        return new Android ();      }    } catch (ClassNotFoundException ignored) {    }< c7/>try {      class.forname ("java.util.Optional");      return new Java8 ();    } catch (ClassNotFoundException ignored) {    }    try {      class.forname (" Org.robovm.apple.foundation.NSObject ");      return new IOS ();    } catch (ClassNotFoundException ignored) {    }    return new Platform ();  }

Visible can be applied to Android, Java8 and iOS platforms, of course, in iOS based on ROBOVM. ROBOVM It is a technology that can run Java applications on iOS devices, primarily in game development.

Retrofit simplifies downloading data from the Web API and parsing it into a common Java object (POJO).

Retrofit important point is that the application of the dynamic agent mechanism in Java http://blog.csdn.net/honghailiang888/article/details/50619545, it is necessary to do a good research:

/** * Create An implementation of the API endpoints defined by the {@code Service} interface. * <p> * The relative path for a given method was obtained from an annotation on the method describing * the Reque St type. The built-in methods is {@link Retrofit2.http.GET GET}, * {@link Retrofit2.http.PUT PUT}, {@link Retrofit2.http.POST PO   ST}, {@link Retrofit2.http.PATCH * PATCH}, {@link Retrofit2.http.HEAD HEAD}, {@link Retrofit2.http.DELETE DELETE} and * {@link Retrofit2.http.OPTIONS OPTIONS}. You can use a custom HTTP method with * {@link http @HTTP}.   For a dynamic URL, omit the path to the annotation and annotate the first * parameter with {@link URL @Url}. * <p> * Method parameters can used to replace parts of the URL by annotating them with * {@link retrofit2.htt P.path @Path}. Replacement sections is denoted by a identifier * Surrounded by curly braces (e.g., "{foo}"). To add items to the query string of a URL use * {@link Retrofit2.http.QueRy @Query}. * <p> * The body of a request is denoted by the {@link retrofit2.http.Body @Body} annotation. The * object is converted to request representation by one of the {@link converter.factory} * instances.   A {@link Requestbody} can also is used for a raw representation. * <p> * Alternative request body formats is supported by method annotations and corresponding * parameter Annot ations: * <ul> * <li>{@link retrofit2.http.FormUrlEncoded @FormUrlEncoded}-form-encoded data with Key-va   Lue * Pairs specified by the {@link Retrofit2.http.Field @Field} parameter annotation. * <li>{@link Retrofit2.http.Multipart @Multipart}-RFC 2388-compliant Multipart data with * parts specified by th   e {@link retrofit2.http.Part @Part} parameter annotation. * </ul> * <p> * Additional static headers can be added for an endpoint using the * {@link retrofit2.http . Headers @Headers} method annotation. For Per-request Control ovER A * header annotate a parameter with {@link header @Header}. * <p> * By default, methods return a {@link call} which represents the HTTP request. The generic * parameter of the call is the response body type and would be a converted by one of the * {@link CONVERTER.F Actory} instances. {@link Responsebody} can also is used for a raw * representation.   {@link Void} can is used if you don't care about the body contents. * <p> * For example: * <pre> * Public interface Categoryservice {* @POST ("category/{cat}/") * C   All<list<item>> categorylist (@Path ("Cat") String A, @Query ("page") int b);  *} * </pre> * * @SuppressWarnings ("unchecked")//Single-interface proxy creation guarded by parameter safety.    Public <T> T Create (final class<t> service) {utils.validateserviceinterface (service);    if (validateeagerly) {eagerlyvalidatemethods (service); } return (T) proxy.newproxyinstance (Service.getclasslOader (), new class<?>[] {service}, new Invocationhandler () {private final Platform Platform = Pla          Tform.get (); @Override public Object Invoke (object proxy, method, Object ... args) throws Throwable {//            If The method is a method from Object then defer to normal invocation.            if (method.getdeclaringclass () = = Object.class) {return Method.invoke (this, args); } if (Platform.isdefaultmethod (method)) {return Platform.invokedefaultmethod (method, service, pro            XY, args);            } Servicemethod Servicemethod = Loadservicemethod (method);            Okhttpcall Okhttpcall = new okhttpcall<> (Servicemethod, args);          Return serviceMethod.callAdapter.adapt (Okhttpcall);  }        }); }

Retrofit relies on okhttp, and the final request response is done in okhttp, and performance is high because of the high performance of Okhttp.

Iii. introduction of Okhttp

The Android Network Framework Okhttp is an open source project that handles network requests and is Android's hottest lightweight framework, contributed by mobile payment square, to replace HttpURLConnection and Apache HttpClient (Android API23 6.0 has removed HttpClient and is now out of play. Website profile: Https://github.com/square/okhttp and http://square.github.io/okhttp/
HTTP is the modern applications network. It ' s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is a HTTP client that's efficient by default:? HTTP/2 support allows all requests to the same host to share a socket.? Connection pooling reduces request latency (if HTTP/2 isn ' t available).? Transparent GZIP shrinks download sizes.? Response caching avoids the network completely for repeat requests. OkHttp Perseveres When the network is troublesome:it would silently recover from common connection problems. If your service has multiple IP addresses OkHttp would attempt alternate addresses if the first connect fails. This is necessary for Ipv4+ipv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails. Using OkHttp is easy. Its Request/response APIs are designed with fluent builders and immutability. It supports both SyNchronous blocking calls and async calls with callbacks. OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7.

Advantage: Allows all requests to connect to the same host address, increasing the efficiency of requests sharing the socket, reducing the number of requests to the server through the connection pool, reducing the request latency cache response data to reduce the duplication of network requests reduces the consumption of data traffic automatically processing gzip compression

Function:

Get,post and other request file upload download load image (internal image size auto-compression) Support request callback, directly return object, object collection support session hold
The okhttp is a direct encapsulated Socket,io stream that is based on the Okio
Iv. introduction of Okio??????

"Android Combat"----from retrofit source analysis to the Java Network Programming and HTTP authoritative guide to think of

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.