Retrofit源码解析(上)
简介
Retrofit是Square公司开发的一款针对Android网络请求的框架,官网地址http://square.github.io/retrofit/ ,在官网上有这样的一句话介绍retrofit,A type-safe HTTP client for Android and Java。我们知道Retrofit底层是基于OKHttp实现的。对okhttp不了解的同学可以看看这一篇文章。okhttp源码解析https://www.cnblogs.com/huangjialin/p/9469373.html
okhttp简单使用
build.gradle依赖
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'
implementation ‘com.squareup.retrofit2:converter-gson:2.4.0'
创建请求接口
/**
* Created by huangjialin on 2018/8/16.
*/ public interface ApiService { @GET("api//Client/GetIsOpen")
Call<SwitchTest> getInformation(); }
这里以GET请求为例,POST请求后面还会提。接口只是为了测试用,返回什么数据,不要在意。接下来看配置Retrofit
package com.example.huangjialin.retrofittest; import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View; import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
testRetrofit();
}
});
} String url = "http://10.31.1.2:93"; public void testRetrofit() {
//创建retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url) //设置baseURl
.addConverterFactory(ScalarsConverterFactory.create()) //增加返回值为String的支持
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<SwitchTest> call = apiService.getInformation();
call.enqueue(new Callback<SwitchTest>() {
@Override
public void onResponse(Call<SwitchTest> call, Response<SwitchTest> response) {
Log.d("huangjialin", "---onResponse----" + response.body().getMessage());
} @Override
public void onFailure(Call<SwitchTest> call, Throwable t) {
Log.d("huangjialin", "--- 失败----" );
}
});
}
}
Model类SwitchTest
package com.example.huangjialin.retrofittest; /**
* Created by huangjialin on 2018/8/16.
*/ class SwitchTest {
private String Message;
private ModelBean Model;
private int ResultType; public String getMessage() {
return Message;
} public void setMessage(String message) {
Message = message;
} public ModelBean getModel() {
return Model;
} public void setModel(ModelBean model) {
Model = model;
} public int getResultType() {
return ResultType;
} public void setResultType(int resultType) {
ResultType = resultType;
} public static class ModelBean {
private boolean Phone;
private boolean Message;
private boolean ClientApp; public boolean isPhone() {
return Phone;
} public void setPhone(boolean phone) {
Phone = phone;
} public boolean isMessage() {
return Message;
} public void setMessage(boolean message) {
Message = message;
} public boolean isClientApp() {
return ClientApp;
} public void setClientApp(boolean clientApp) {
ClientApp = clientApp;
}
} }
最后记得加上网络权限
<uses-permission android:name=“android.permission.INTERNET"/>
retrofit一个简单的网络请求就可以了……当然,我这里的url是用我司的测试地址,是有网络权限的,所以记得替换成你们自己的地址。使用比较简单,这里不做过多的解释。下面我们看看retrofit的注解
请求方法
http请求方式一共有7种,分别是GET,POST、PUT、DELETE、HEAD、OPTIONS、PATCH,而其中我们最常用的就是get和post请求,这里也主要拿这两种方式分析。retrofit设置请求方法主要是通过注解的方式
get请求
@GET("api//Client/GetIsOpen")
Call<SwitchTest> getInformation();
post请求
@POST("api/login/GetModel")
Call<LoginModel> login(@Body Login login);
只需要在每个请求接口上方加上@GET(“aaaa”)或者是@POST(“aaaa”)就可以设置不同请求方式。retrofit除了可以通过注解的方式设置请求方法外,还可以通过注解来设置请求参数。
GET网络请求注解参数方式
@Query
@GET("api//Client/GetIsOpen")
Call<SwitchTest> getInformation(@Query("id") String id,@Query("page") int page);
这种方式会将这些请求参数附加到URL后面,也就是拼接起来。如上面设置的,最后会成为api//Client/GetIsOpen/id/page,当然,如果参数很多,可以使用下面这种方式
@QueryMap
@GET("api//Client/GetIsOpen")
Call<SwitchTest> getInformation(@QueryMap Map<String,String> parame);
这种方式可以将参数全部存放到Map中,源码中是这样解释QueryMap的Query parameter keys and values appended to the URL.意思是会将这个key值拼接到url上面。
除了可以拼接参数以外,还可以动态的拼接URL地址,使用@Path
@Path
源码这样介绍Named replacement in a URL path segment. Values are converted to strings using
@GET("api//Client/{path}")
Call<SwitchTest> pathTest(@Path("path")String path);
这样我们在调用这个接口的时候,传入的参数就会替换这个path。
POST网络请求注解参数方式
我们知道,post请求的参数不是以拼接的形式的,而是将参数放到请求体中的,所以retrofit注解post请求的参数是以另外的方式
@Body
源码是这样解释的Use this annotation on a service method param when you want to directly control the request body,意思是当您想要直接控制请求体时,在服务方法参数上使用此注释
@POST("api/login/GetModel")
Call<LoginModel> login(@Body Login login);
其中Login是一个实体类,上面这个接口api/login/GetModel,是一个登陆接口,登陆就需要账号密码,所以这个实体类就可以这样设置。
package com.example.huangjialin.retrofittest; /**
* Created by huangjialin on 2018/8/16.
*/ public class Login {
private String tel;
private String password; public Login(String tel, String password) {
this.tel = tel;
this.password = password;
}
}
当我们调用这个接口时,就可以传入new Login(“账号”,”密码”);
@Field
源码是这样解释的:Named pair for a form-encoded request.
@FormUrlEncoded
@POST("api/login/GetModel")
Call<LoginModel> login(@Field("tel") String tel,
@Field("password") String password);
这里需要注意一个地方使用@Field的时候,一定要记得加上@FormUrlEncoded,这个作用是表示请求主体将使用表单URL编码。
@FieldMap
源码是这样解释的:Named key/value pairs for a form-encoded request.翻译就是:表单编码请求的命名键/值对。简单一点的理解就是这样FieldMap可以将参数全部存放到map中。
@FormUrlEncoded
@POST("api/login/GetModel")
Call<LoginModel> login(@FieldMap Map<String,String>parame);
@Part
源码是这样解释的:Denotes a single part of a multi-part request.
@Multipart
@POST("user/photo")
Call<实体类> updateUser(@Part MultipartBody.Part photo, @Part("description") RequestBody description);
其中使用@Part 一定要记得加上@Multipart 源码是这样解释这个的Denotes that the request body is multi-part. Parts should be declared as parameters and annotated with {@link Part @Part}. 表示请求主体是多部分的。部件应该声明为参数和 注释为{@link Part @Part}。当然使用@Part 主要是用来上传文件的,并且是单文件上传的。如果多文件上传的话,可以使用下面这个
@PartMap
源码是这样解释的:Denotes name and value parts of a multi-part request.
@Multipart
@POST("user/photo")
Call<实体类> updateUser(@PartMap Map<String, RequestBody> photos,
@Part("description") RequestBody description);
除了上面这些注解外,我们往往还能看到这个注解
@Headers
@Headers("Cache-Control: max-age=640000")
@POST("api/login/GetModel")
Call<LoginModel> login(@Body Login login);
源码的解释和例子是这样的
/**
* Adds headers literally supplied in the {@code value}.
* <pre><code>
* @Headers("Cache-Control: max-age=640000")
* @GET("/")
* ...
*
* @Headers({
* "X-Foo: Bar",
* "X-Ping: Pong"
* })
* @GET("/")
* ...
* </code></pre>
* <strong>Note:</strong> Headers do not overwrite each other. All headers with the same name will
* be included in the request.
*
* @see Header
* @see HeaderMap
*/
有什么用的呢??在http请求中,为了防止攻击或是过滤掉不安全的访问或是添加特殊加密的访问等等,用来减轻服务器的压力和保证请求的安全等,就会在请求头上面加一些内容。
本来,想弄成一篇文章的,但是写完到这里以后,感觉篇幅好长,所以在这里分一下篇幅吧
Retrofit源码解析(下)https://www.cnblogs.com/huangjialin/p/9492271.html
Retrofit源码解析(上)的更多相关文章
- Retrofit源码解析(下)
接着上一章继续分析上一章主要简单说了一下基本使用和注解,这一章,我们主要看源码,废话不多说了,直接上.先上一张图 从网络上拿来的 前面一章说了一下Retrofit的简单使用https://www.cn ...
- Laravel学习笔记之Session源码解析(上)
说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助.Laravel在web middleware中定义了 ...
- spring源码解析--上
本文是作者原创,版权归作者所有.若要转载,请注明出处. 首先是配置类 package com.lusai.config; import org.springframework.context.anno ...
- RxJava + Retrofit源码解析
RxJava + Retrofit怎么请求网络,具体的用法这里就不讲了,本文只讲一些重点源码. 版本如下: okhttp : "com.squareup.okhttp3:okhttp:3.1 ...
- tinyxml源码解析(上)
转载于:http://www.cnblogs.com/marchtea/archive/2012/11/09/2762669.html 前言: 前段时间做功能可行性的时候简单的使用了tinyxml.在 ...
- FMDB源码解析(上)-FMDB基本使用
目录 一: 初识FMDB 二: 基本使用 三: 基本操作 结束 最后更新:2017-02-22 2017, 说到做到 一: 初识FMDB FMDB是iOS平台的SQLite数据库框架 FMDB以OC的 ...
- Retrofit源码设计模式解析(上)
Retrofit通过注解的方法标记HTTP请求参数,支持常用HTTP方法,统一返回值解析,支持异步/同步的请求方式,将HTTP请求对象化,参数化.真正执行网络访问的是Okhttp,Okhttp支持HT ...
- Kakfa揭秘 Day9 KafkaReceiver源码解析
Kakfa揭秘 Day9 KafkaReceiver源码解析 上一节课中,谈了Direct的方式来访问kafka的Broker,今天主要来谈一下,另一种方式,也就是KafkaReceiver. 初始化 ...
- tinyxml源码解析(中)
转载于:http://www.cnblogs.com/marchtea/archive/2012/11/20/2766756.html 前言: 之前趁着这段时间比较空闲,也因为听闻tinyxml大名, ...
随机推荐
- workerman使用
1.start_timer.php(boc) <?php use \Workerman\Worker; use \Workerman\Lib\Timer; require_once '/var/ ...
- [SoapUI] Tips and Tricks(提示和技巧)
https://www.soapui.org/scripting-properties/tips-tricks.html
- Jmeter 如何让变量中包含变量
在运行Jmeter的过程中,有时候,我们可能会引用一个变量,而这个变量又是由另外一个变量组成的: 譬如我在脚本中要引用变量MappingData1,按照正常的情况,直接就是用${MappingData ...
- 在命令提示符(cmd)下怎样复制粘贴
我们把鼠标放在面板的上方,右击,界面显示如下: 我们选择“属性”,单击,界面显示如下: 我们点选“快速编辑模式”,再点击“确定”,这样设置就完成了,界面显示如下: 我们在面板中随意选择 ...
- 更新vs2017 15.9.2后,在指定-T v141_xp情况下载编译会报下面warning MSB8051
更新vs2017 15.9.2后,在指定-T v141_xp情况下载编译会报下面warning: C:\Program Files (x86)\Microsoft Visual Studio\2017 ...
- 2018.09.27 bzoj3029: 守卫者的挑战(概率dp)
传送门 概率dp经典题目. 直接f[i][j][k]f[i][j][k]f[i][j][k]表示当前是第i次挑战,已经胜利了j次,目前的背包剩余空间是k. 然后用前面的转移后面的就行了. 注意第三维可 ...
- 2018.06.30 BZOJ3083: 遥远的国度(换根树剖)
3083: 遥远的国度 Time Limit: 10 Sec Memory Limit: 512 MB Description 描述 zcwwzdjn在追杀十分sb的zhx,而zhx逃入了一个遥远的国 ...
- 2017 pycharm 激活码
BIG3CLIK6F-eyJsaWNlbnNlSWQiOiJCSUczQ0xJSzZGIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiI ...
- Codeforces735C Tennis Championship 2016-12-13 12:06 77人阅读 评论(0) 收藏
C. Tennis Championship time limit per test 2 seconds memory limit per test 256 megabytes input stand ...
- ubuntu18.04 编译安装 apache php
1. apache apache 需要依赖几个模块:apr, apr-util, pcre,也分别源码安装. 1.1 编译安装 1.1.1 apr apr-util 下载地址:http://apr.a ...