Retorift的基本用法

Author Avatar
weechan 3月 25, 2018

Retrofi2

标签(空格分隔): android


1
2
3
4
5
//导入依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
1
2
3
4
5
6
7
8
9
//Retrofit基础配置
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
//GsonConverterFactory.create()提供Gson支持,可以添加多种序列化Factory,
//RxJavaCallAdapterFactory.create() rxjava支持

retrofit注解解析:
方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP。
标记注解,包含@FormUrlEncoded、@Multipart、@Streaming
参数注解,包含@Query,@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap
其他注解,包含@Path、@Header,@Headers、@Url


@Streaming:用于下载大文件
@Url:使用全路径复写baseUrl,适用于非统一baseUrl的场景。

1
2
3
@Streaming
@GET
Call<ResponseBody> download(@Url String url);


@Path:URL占位符,用于替换和动态更新,相应的参数必须使用相同的字符串被@Path进行注释
@Query,@QueryMap:查询参数,用于GET查询,需要注意的是@QueryMap可以约定是否需要encode

1
2
3
@GET("group{gid}/users")
Call<List<User>> getGroupList( @Path("gid") int groupId);
//--> http://baseurl/group/groupId/users


@Body:用于POST请求体,将实例对象转换为对应的json字符串参数.
@Header:header处理,不能被互相覆盖,用于修饰参数.
@Headers 用于修饰方法,用于设置多个Header值:

1
2
3
4
5
6
7
8
@POST("add")
Call<List<User>> addUser(@Body User user,@Header("Authorization") String authorization);

@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);


1
2
3
4
5
6
//基础用法
1.定义接口,实体类->用于json
public interface KugouApi {
@GET("song_search_v2?")
Call<List<Repo>> listRepos(@Path("user") String user);
}

拦截器 Interceptor

拦截器,可用于对请求前对Request进行检查,请求后对Response进行检查.以达到重写,修改请求,返回的目的.
比如 修改请求头,响应头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new CookieInterceptor()).build();
new Retrofit.Builder().client(okHttpClient)
//构建带拦截器的OkhttpClient传入Retrofit


//一个简易的保持服务端Seesion会话的拦截器
public class CookieInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {

String cookie;
Request request;
Response response;

//cookieMgr 其实是SharePreference的封装类
if(!(cookie = App.cookieMgr.get("Set-Cookie","")).equals("")){
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("Cookie",cookie);
request = builder.build();
Log.e("CookieInterceptor",cookie);
}else{
request = chain.request();
}

response = chain.proceed(request);

if(response.header("Set-Cookie") != null){
App.cookieMgr.clear("Set-Cookie");
App.cookieMgr.save("Set-Cookie",response.header("Set-Cookie"));
}

return response;
}
}

原理:
当用户是首次发起请求的时候(其实就是没有带cookie),这时候响应头会返回一个cookie值,该值含有JSESSIONID,此时将该值保存到本地,在以后的访问接口过程中把存在本地的值取出来,然后加到请求头上面就可以了