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大名, ...
随机推荐
- PAT 1065 单身狗(25)(STL-map+思路+测试点分析)
1065 单身狗(25 分) "单身狗"是中文对于单身人士的一种爱称.本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱. 输入格式: 输入第一行给出一个正整数 N(≤ ...
- Codeforces 681C. Heap Operations 优先队列
C. Heap Operations time limit per test:1 second memory limit per test:256 megabytes input:standard i ...
- dedecms操作数据库
重要的事情说三遍:代码复制完要格式化,格式化,格式化,最好重新抄一遍,小心陷阱 一.配置数据库配置文件路径/data/common.inc.php二.连接数据库dirname(__FILE__)表示当 ...
- CreateMutex用法
1. CreateMutex只是创建了一把锁, 这把锁你用来锁门还是锁抽屉还是锁你对象的内裤都由你自己决定. 2. lpName是指定这把锁的名字. 你要不给这把锁取个名字都可以. 只是有了相 ...
- 并发编程(三)Promise, Future 和 Callback
并发编程(三)Promise, Future 和 Callback 异步操作的有两个经典接口:Future 和 Promise,其中的 Future 表示一个可能还没有实际完成的异步任务的结果,针对这 ...
- c++11日志练习
/************************************************************** 技术博客 http://www.cnblogs.com/itdef/ ...
- 2018.09.22 牧场的安排(状压dp)
描述 农民 John 购买了一处肥沃的矩形牧场,分成M*N(1 <= M <= 12; 1 <= N <= 12)个 格子.他想在那里的一些格子中种植美味的玉米.遗憾的是,有些 ...
- [转]谈谈 Mifare Classic 破解
Mifare Classic 提供 1 Kb - 4Kb 的容量,现在国内采用的多数是 Mifare Classic 1k(S50)[后面简称 M1 卡] M1 卡有从 0 到 15 共 16 个扇区 ...
- web大文件上传(web应用---SSH框架)
版权所有 2009-2018荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webapp/up6.2/in ...
- Android ContentProvider和Uri详解
一.使用ContentProvider(内容提供者)共享数据 ContentProvider在android中的作用是对外共享数据, 也就是说你可以通过ContentProvider把应用中的数据共享 ...