[置顶] 【Android实战】----从Retrofit源码分析到Java网络编程以及HTTP权威指南想到的
一、简介
接上一篇【Android实战】----基于Retrofit实现多图片/文件、图文上传中曾说非常想搞明白为什么Retrofit那么屌。最近也看了一些其源码分析的文章以及亲自查看了源码,发现其对Java网络编程及HTTP权威指南有了一个很好的诠释。一直以来,都信奉一个原则,在这个新技术日新月异的时代,如何在Java界立足,凭借的就两点:
1、基本功,包括:Java基本知识,(Java编程思想、Effective Java),Java进阶(Java虚拟机、Java设计模式)、网络相关(这个时代没有网络就没有一切,Java网络编程、HTTP权威指南、TCP/IP协议),计算机系统相关(编译原理、深入理解计算机系统等)这些都是根本,所谓万变不离其宗,在掌握这些基本功的基础上,再学习新技术,面对日新月异的新技术时就会游刃有余。
2、将琐碎知识串联起来的能力,也就是归纳总结能力。无论是在工作中还是学习中,起初用到的知识是东一块、西一块,其实许多东西都是关联的,通过系统的梳理形成自己的知识体系,打造属于自己的专属领域,这也是在Java界立足的根本。
以上这些纯属自己这段时间的瞎想胡扯,大家共勉。
二、Retrofit简介
可参见Jake Wharton的演讲https://realm.io/cn/news/droidcon-jake-wharton-simple-http-retrofit-2/
retrofit是由square公司开发的。square在github上发布了很多优秀的Android开源项目。例如:otto(事件总线),leakcanary(排查内存泄露),android-times-square(日历控件),dagger(依赖注入),picasso(异步加载图片),okhttp(网络请求),retrofit(网络请求)等等。更多square上的开源项目我们可以去square的GitHub进行查看。
根据Retrofit的官方文档(https://github.com/square/retrofit及http://square.github.io/retrofit/)看Retrofit是
A type-safe HTTP client for Android and Java
可见Retrofit可以应用到Android平台和Java平台中,其源码中也可看出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) {
}
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();
}
可见可以应用在Android、Java8及IOS平台中,当然在IOS中要基于RoboVM。RoboVM它是一种可以在iOS设备上运行Java应用程序的技术,这种技术主要还是用于在游戏开发中。
Retrofit简化了从Web API下载数据,解析成普通的Java对象(POJO)。
Retrofit重要的一点是应用了Java中的动态代理机制http://blog.csdn.net/honghailiang888/article/details/50619545,有必要好好研究下:
/**
* Create an implementation of the API endpoints defined by the {@code service} interface.
* <p>
* The relative path for a given method is obtained from an annotation on the method describing
* the request type. The built-in methods are {@link retrofit2.http.GET GET},
* {@link retrofit2.http.PUT PUT}, {@link retrofit2.http.POST POST}, {@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 on the annotation and annotate the first
* parameter with {@link Url @Url}.
* <p>
* Method parameters can be used to replace parts of the URL by annotating them with
* {@link retrofit2.http.Path @Path}. Replacement sections are denoted by an 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 will be converted to request representation by one of the {@link Converter.Factory}
* instances. A {@link RequestBody} can also be used for a raw representation.
* <p>
* Alternative request body formats are supported by method annotations and corresponding
* parameter annotations:
* <ul>
* <li>{@link retrofit2.http.FormUrlEncoded @FormUrlEncoded} - Form-encoded data with key-value
* 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 the {@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 will be converted by one of the
* {@link Converter.Factory} instances. {@link ResponseBody} can also be used for a raw
* representation. {@link Void} can be used if you do not care about the body contents.
* <p>
* For example:
* <pre>
* public interface CategoryService {
* @POST("category/{cat}/")
* Call<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 = Platform.get();
@Override public Object invoke(Object proxy, Method 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, proxy, args);
}
ServiceMethod serviceMethod = loadServiceMethod(method);
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
Retrofit依赖于OkHttp,最终的请求响应是在OkHttp中做的,性能之所以高,也是因为okHttp的性能高。
三、OkHttp简介
HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an 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 will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will 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 API is 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.
功能:
四、Okio简介
Okio is a new library that complements java.io and java.nio to make it much easier to access, store, and process your data.
[置顶] 【Android实战】----从Retrofit源码分析到Java网络编程以及HTTP权威指南想到的的更多相关文章
- 【Android实战】----从Retrofit源代码分析到Java网络编程以及HTTP权威指南想到的
一.简单介绍 接上一篇[Android实战]----基于Retrofit实现多图片/文件.图文上传中曾说非常想搞明确为什么Retrofit那么屌. 近期也看了一些其源代码分析的文章以及亲自查看了源代码 ...
- Retrofit源码分析(一)
1.基本用法 创建接口 public interface GitHubService { @GET("users/{user}/repos") Observable<List ...
- Android事件分发机制源码分析
Android事件分发机制源码分析 Android事件分发机制源码分析 Part1事件来源以及传递顺序 Activity分发事件源码 PhoneWindow分发事件源码 小结 Part2ViewGro ...
- JVM源码分析之Java对象头实现
原创申明:本文由公众号[猿灯塔]原创,转载请说明出处标注 “365篇原创计划”第十一篇. 今天呢!灯塔君跟大家讲: JVM源码分析之Java对象头实现 HotSpot虚拟机中,对象在内存中的布局分为三 ...
- [旧][Android] Retrofit 源码分析之 ServiceMethod 对象
备注 原发表于2016.05.03,资料已过时,仅作备份,谨慎参考 前言 大家好,我又来学习 Retrofit 了,可能这是最后一篇关于 Retrofit 框架的文章了.我发现源码分析这回事,当时看明 ...
- Android 自定义View及其在布局文件中的使用示例(三):结合Android 4.4.2_r1源码分析onMeasure过程
转载请注明出处 http://www.cnblogs.com/crashmaker/p/3549365.html From crash_coder linguowu linguowu0622@gami ...
- android高级---->AsyncTask的源码分析
在Android中实现异步任务机制有两种方式,Handler和AsyncTask,它在子线程更新UI的例子可以参见我的博客(android基础---->子线程更新UI).今天我们通过一个小的案例 ...
- Android异步消息传递机制源码分析
1.Android异步消息传递机制有以下两个方式:(异步消息传递来解决线程通信问题) handler 和 AsyncTask 2.handler官方解释的用途: 1).定时任务:通过handler.p ...
- Android面试题-OkHttp3源码分析
本文配套视频: okhttp内核分析配套视频一 okhttp内核分析配套视频二 okhttp内核分析配套视频三 源码分析相关面试题 Volley源码分析 注解框架实现原理 基本使用 从使用方法出发,首 ...
随机推荐
- 浅谈 JS 内存泄露方式与避免方法(二)
Concept WHAT : 内存泄露是指一块被分配的内存既不能使用,又不能回收,直到浏览器进程结束.正常情况下,垃圾回收器在DOM元素和event处理器不被引用或访问的时候回收它们.但是,IE的早些 ...
- 第一课 C语言简明教程
1序言: 1与Java.C#等高级语言相比,C语言使用简单但是也非常重要更容易出错,到目前为止基本上操作系统的内核代码超过百分之九十使用C语言完成,因此学好C语言是学好计算机这门课程的基础,特别是进入 ...
- POJ - 2912 Rochambeau (带权并查集+枚举)
题意:有N个人被分为了三组,其中有一个人是开了挂的.同组的人的关系是‘=’,不同组的人关系是‘<’或'>',但是开了挂的人可以给出自己和他人任意的关系.现在要根据M条关系找出这个开了挂的人 ...
- SSO 单点登录的实现原理
单点登录SSO(Single Sign On)说得简单点就是在一个多系统共存的环境下,用户在一处登录后,就不用在其他系统中登录,也就是用户的一次登录能得到其他所有系统的信任.单点登录在大型网站里使用得 ...
- redis 学习笔记(二)
1. 在centos下安装g++,如果输入 yum install g++,那么将会提示找不到g++.因为在centos下g++安装包名字叫做:gcc-c++ 所以应该输入 yum install g ...
- iconfont的使用
首先你要有一个图标库的账号,我们使用的是阿里矢量图标库,其次你要有一套已经设计好的图标原图.如果你具备了这些,就可以和我一起看iconfont的使用姿势了. 写在前面 不结合其他矢量库或UI框架一起使 ...
- Ubuntu启动文件破坏启动恢复方法
reboot后主机登录显示如下图: 解决步骤: 1.fs0:(回车) 2.edit startup.nsh 3.添加下面字段: fs0: cd EFI/ubuntu grubx64.efi 4.重启即 ...
- LVS持久化
在实际应用场景中,轮询调度并不都是适用的.有些情况下,需要我们把同一个会话的请求都调度给一个RS节点.这时候就需要LVS提供持久化的能力,能够实现会话保持. 一.LVS的持久化主要包括以下两个方面. ...
- Your app uses or references the following non-public APIs的解决方案
之前接了一个旧的项目,代码混乱,年代久远,不得不吐槽一波,好不容易改完需求提交代码,说用到了non-public APIs,搞了好久终于找到地方了,下面是我的解决过程,让大家少走弯路: 下面的被驳回的 ...
- 定制swagger的UI
https://github.com/RSuter/NSwag/wiki#ways-to-use-the-toolchain Customizations Swagger generation: Yo ...