1.Retrofit2概述
Retrofit框架是Square公司出品的目前非常流行的网络框架.
效率高,实现简单,运用注解和动态代理.
极大简化了网络请求的繁琐步骤,非常适合REST ful网络请求.
目前Retofit版本是2Retrofit其实我们可以理解为OkHttp的加强版。
它也是一个网络加载框架。底层是使用OKHttp封装的。
准确来说,网络请求的工作本质上是OkHttp完成,而 Retrofit 仅负责网络请求接口的封装。
它的一个特点是包含了特别多注解,方便简化你的代码量。
并且还支持很多的开源库(著名例子:Retrofit + RxJava)
2.Retrofit2的好处
- 超级解耦
解耦?解什么耦?
我们在请求接口数据的时候,API接口定义和API接口使用总是相互影响,什么传参、回调等,耦合在一块。有时候我们会考虑一下怎么封装我们的代码让这两个东西不那么耦合,这个就是Retrofit的解耦目标,也是它的最大的特点。 - 可以配置不同HttpClient来实现网络请求,如OkHttp、HttpClient...
- 支持同步、异步和RxJava
- 可以配置不同的反序列化工具来解析数据,如json、xml...
- 请求速度快,使用非常方便灵活
3.Retrofit2配置
- 官网
- 依赖:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
- 添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
4,Retrofit2的使用步骤
- 定义接口类(封装URL地址和数据请求)
- 实例化Retrofit
- 通过Retrofit实例创建接口服务对象
- 接口服务对象调用接口中的方法,获取Call对象
- Call对象执行请求(异步、同步请求)
6.Retrofit2发送GET、POST请求(异步、同步)
- Retrofit2发送GET
//主机地址
String url = "http://apicloud.mob.com/appstore/health/search?key=1ac78a8602d58&name=转氨酶";
String BASE_URL = "http://apicloud.mob.com/appstore/health/";//必须以反斜杠结尾
//接口服务
public interface BigFlyServer {
//GET
@GET("search?key=1ac78a8602d58&name=转氨酶")
Call<ResponseBody> getData1();
@GET("search?")
Call<ResponseBody> getData2(@Query("key") String key,@Query("name") String key);
@GET("search?")
Call<ResponseBody> getData3(@QueryMap Map<String,Object> map);
}
//Get异步
private void initGetEnqueue() {
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.获取MyServer接口服务对象
MyServer myServer = retrofit.create(MyServer.class);
//3.获取Call对象
//方式一
Call<ResponseBody> call1 = myServer.getData1();
//方式二
Call<ResponseBody> call2 = myServer.getData2("908ca46881994ffaa6ca20b31755b675");
//方式三
Map<String,Object> map = new HashMap<>();
map.put("appKey","908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call = myServer.getData3(map);
//4.Call对象执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默认直接回调主线程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
//GET同步
private void initGetExecute() {
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.获取MyServer接口服务对象
MyServer myServer = retrofit.create(MyServer.class);
//3.获取Call对象
final Call<ResponseBody> call = myServer.getData1();
new Thread(){//子线程执行
@Override
public void run() {
super.run();
try {
//4.Call对象执行请求
Response<ResponseBody> response = call.execute();
final String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(result);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
2.Retrofit2发送POST
String URL = "http://apicloud.mob.com/appstore/health/";//必须以反斜杠结尾
public interface MyServer {
//POST("search?") POST("search")相同
@POST("search?")
@FormUrlEncoded
Call<ResponseBody> postData1(@Field("key") String appKey,@Field("name") String appKey);
@POST("search")
@FormUrlEncoded
Call<ResponseBody> postData2(@FieldMap Map<String,Object> map);
}
//POST异步
private void initPostEnqueue() {
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.获取MyServer接口服务对象
MyServer myServer = retrofit.create(MyServer.class);
//3.获取Call对象
//方式一
Call<ResponseBody> call1 = myServer.postData1("908ca46881994ffaa6ca20b31755b675");
//方式二
Map<String,Object> map = new HashMap<>();
map.put("appKey","908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call = myServer.postData2(map);
//4.Call对象执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默认直接回调主线程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
7.Retrofit注解
注解代码 请求格式
请求方式:
@GET GET请求
@POST POST请求
@DELETE DELETE请求
@HEAD HEAD请求
@OPTIONS OPTIONS请求
@PATCH PATCH请求
请求头:
@Headers("K:V") 添加请求头,作用于方法
@Header("K") 添加请求头,参数添加头
@FormUrlEncoded 用表单数据提交,搭配参数使用
@Stream 下载
@Multipart 用文件上传提交 multipart/form-data
请求参数:
@Query 替代参数值,通常是结合get请求的
@QueryMap 替代参数值,通常是结合get请求的
@Field 替换参数值,是结合post请求的
@FieldMap 替换参数值,是结合post请求的
请求路径:
@Path 替换路径
@Url 路径拼接
请求体:
@Body(RequestBody) 设置请求体,是结合post请求的
文件处理:
@Part Multipart.Part
@Part("key") RequestBody requestBody(单参)
@PartMap Map<String,RequestBody> requestBodyMap(多参)
@Body RequestBody requestBody(自定义参数)
8.Retrofit2其他常用注解使用
String URL = "http://api.shujuzhihui.cn/api/news/";//必须以反斜杠结尾
public interface MyServer {
//Path,不能替换参数,必须路径中字符
@GET("wages/{wageId}/detail")
Call<ResponseBody >getImgData(@Path("wageId") String wageId);
//Url
//@Url cannot be used with @GET URL (parameter #1),如果使用url注解,get注解为空
@GET
Call<ResponseBody >getImgData(@Url String url);
@GET
Call<ResponseBody >getImgData(@Url String url,@Query("appKey") String appkey);
//Json
@POST("categories")
@Headers("Content-Type:application/json")
Call<ResponseBody> getFormDataJson(@Body RequestBody requestBody);
//Form
@POST("categories")
@Headers("Content-Type:application/x-www-form-urlencoded")
Call<ResponseBody> getFormData1(@Body RequestBody requestBody);
//复用URL
@POST()
@Headers("Content-Type:application/x-www-form-urlencoded")
Call<ResponseBody> getFormData2(@Url String url,@Body RequestBody requestBody);
//通用
@POST()
Call<ResponseBody> getFormData3(@Url String url, @Body RequestBody requestBody, @Header("Content-Type") String contentType);
}
//RequestBody参数拼接
private void initPostBody() {
Retrofit.Builder builder = new Retrofit.Builder();
Retrofit retrofit = builder.baseUrl(MyServer.URL)
.build();
MyServer myServer = retrofit.create(MyServer.class);
//Json类型
String json1 = "{\n" + " \"appKey\": \"908ca46881994ffaa6ca20b31755b675\"\n" + "}";
RequestBody requestBody01 = RequestBody.create(MediaType.parse("application/json,charset-UTF-8"),json1);
Call<ResponseBody> call01 = myServer.getFormDataJson(requestBody01);
//String类型
//有参形式
RequestBody requestBody02 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"appKey=908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call02 = myServer.getFormData1(requestBody02);
//无参形式
RequestBody requestBody3 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"");
Call<ResponseBody> call03 = myServer.getFormData1(requestBody3);
//RequestBody (Form表单,键值对参数形式)
//方式一(requestBody)
FormBody requestBody = new FormBody.Builder()
.add("appKey","908ca46881994ffaa6ca20b31755b675")
.build();
Call<ResponseBody> call1 = myServer.getFormData1(requestBody);
//方式二(url+requestBody)
FormBody requestBody = new FormBody.Builder()
.add("appKey","908ca46881994ffaa6ca20b31755b675")
.build();
Call<ResponseBody> call2 = myServer.getFormData2("categories",requestBody);
//方式三(url+requestBody+header)
FormBody requestBody = new FormBody.Builder()
.add("appKey","908ca46881994ffaa6ca20b31755b675")
.build();
Call<ResponseBody> call3 = myServer.getFormData3("categories",requestBody,"application/x-www-form-urlencoded");
call3.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默认直接回调主线程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
9.数据解析器(Converter)
- Retrofit支持多种数据解析方式
- 使用时需要在Gradle添加依赖
Gson:com.squareup.retrofit2:converter-gson:2.0.2
Jackson:com.squareup.retrofit2:converter-jackson:2.0.2
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(MyService.URL)
.build();
10.网络请求适配器(CallAdapter)
- Retrofit支持多种网络请求适配器方式:guava、Java8和rxjava
guava:com.squareup.retrofit2:adapter-guava:2.0.2
Java8:com.squareup.retrofit2:adapter-java8:2.0.2
rxjava:com.squareup.retrofit2:adapter-rxjava:2.0.2
11.Retrofit2文件上传
String FileUpLoadURL = "http://yun918.cn/study/public/";
public interface MyServer {
@POST("file_upload.php")
@Multipart
Call<ResponseBody> upLoadFile1(@Part MultipartBody.Part part,@Part("key") RequestBody requestBody);//单参
@POST("file_upload.php")
@Multipart
Call<ResponseBody> upLoadFile2(@Part MultipartBody.Part part, @PartMap Map<String,RequestBody> requestBodyMap); //多参
@POST("file_upload.php")
@Multipart
Call<ResponseBody> upLoadFile3(@Body RequestBody requestBody); //自定义
}
//文件上传
private void initPostFile() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.FileUpLoadURL)
.build();
MyServer myServer = retrofit.create(MyServer.class);
Call<ResponseBody> call = null;
//上传文件路径
File file = new File("/sdcard/Pictures/Screenshorts/dd.png");
if(file.exists()){
//方式一
RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/png"),file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody1);
RequestBody responseBody2 = RequestBody.create(MediaType.parse("multipart/form-data"),"abc");
call = myServer.upLoadFile1(part, responseBody2);
//方式二
MultipartBody.Builder builder1 = new MultipartBody.Builder().setType(MultipartBody.FORM);
MultipartBody body = builder1.addFormDataPart("key", "abc")
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"),file))
.build();
call = myServer.upLoadFile3(body);
//方式三
MultipartBody.Part part2 = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/png"),file));
Map<String, RequestBody> map = new HashMap<>();
RequestBody responseBody3 = RequestBody.create(MediaType.parse("multipart/form-data"),"abc");
map.put("key",responseBody3);
call = myServer.upLoadFile2(part2, map);
}
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默认直接回调主线程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}
12.Form表单语法
1、Form表单语法
在Form元素的语法中,EncType表明提交数据的格式 用 Enctype 属性指定将数据回发到服务器时浏览器使用的编码类型。
1,application/x-www-form-urlencoded: 窗体数据被编码为名称/值对。这是标准的编码格式。
2,multipart/form-data: 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分,这个一般文件上传时用。
3,text/plain: 窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符。
2、常用的编码方式
form的enctype属性为编码方式,常用有两种:
application/x-www-form-urlencoded(默认)
multipart/form-data
1.x-www-form-urlencoded
浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2…)
2.multipart/form-data
浏览器把form数据封装到http body中,然后发送到server。如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。但是如果type=file的话,就要用到multipart/form-data了。
11.Retrofit2及OkHttp3的区别
Retrofit2使用注解设置请求内容
Retrofit2回调主线程,OkHttp3回调子线程
Retrofit2可以做数据解析转换
Retrofit2可以使用在REST ful网络请求.
12.Retrofit2源码分析(底层OkHttp3,注解了解,反射了解)
构建者构建
动态代理、反射
注解配置请求
底层基于OkHttpCall调用
源码解析:
1.点击builder,平台选择(platform)、获取工厂、baseURL
platform = Platform.get();
callFactory = retrofit.callFactory;
baseUrl = retrofit.baseUrl;
2.点击build方法
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
//可以选择客户端,如果传的callFactory是空,默认创建一个ok
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
//线程池,主要做线程切换
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// 添加一个网络切换器
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
// 添加一个数据切换工厂
List<Converter.Factory> converterFactories = new ArrayList<>(
1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
//最后添加完工厂返回一个retrofit对象
`
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
- MyService myService = retrofit.create(MyService.class);
用到了动态代理(Proxy.newProxyInstance)及反射
Proxy.newProxyInstance获取动态代理单例,里边有三个参数,
第一个是代理对象,第二个参数是调用的方法,第三个是方法的参数
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
private final Object[] emptyArgs = new Object[0];
@Override public Object invoke(Object proxy, Method method, @Nullable 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);
}
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
ServiceMethod<?> loadServiceMethod(Method method) {
ServiceMethod<?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
result = ServiceMethod.parseAnnotations(this, method);
进方法里边看,RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
工厂模式,看工厂是这么build出来的
遍历注解
ServiceMethod中返回的东西
HttpServiceMethod
@Override ReturnT invoke(Object[] args) {
return callAdapter.adapt(
new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}
OkHttpCall----enqueue-- response = parseResponse(rawResponse);
T body = responseConverter.convert(catchingBody);