您的位置:首页 > 理论基础 > 计算机网络

Retrofit2使用总结

2017-05-10 16:14 260 查看
了解Retrofit2:
1)其本质上就是对okHttp的封装,使用面向接口的方式进行网络请求。
2)使用注解和动态代理,极大的简化网络请求的步骤。
3)默认使用OKHttp处理网络请求,默认使用Gson解析(可以自定义)

Retrofit2常用的注解接口:

@Post:表示为post请求方式

@Get:表示为get请求方式

@FormUrlEncoded:以表单的形式提交请求参数

@FieldMap:指定所有集合表单控件的名称,login (@FieldMap Map<String,String> map)  以map集合的形式提交表单数据

BaseUrl与@url的区别: BaseUrl最好以 / 结尾,而@url最好别以 / 开头

Retrofit2代码实现步骤

1)定义一个接口(主要作用是用注解的形式封装请求地址和请求参数),比如UserApi

2)实例化Retrofit 

3)通过Retrofit实例,获取一个接口服务对象: create(UserApi.class)

4)通过接口服务对象ApiService,调用接口中的方法,获取call对象

5)Call对象执行请求(异步请求、同步请求)

UaseApi: 接口的创建,主要用于封装一个模块中,多个请求接口,其中包含请求参数,请求方式,请求URL,请求方法名

添加依赖:

//添加依赖jackson依赖
compile 'com.squareup.retrofit2:converter-jackson:2.0.1'
//添加retrofit2依赖
compile 'com.squareup.retrofit2:retrofit:2.0.1'
//添加日志信息拦截依赖
compile 'com.squareup.okhttp3:logging-interceptor:3.7.0'
//添加对rxJava的支持
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'io.reactivex:rxandroid:1.1.0'
//ButterKnife 7.0.1对应sdk24
compile 'com.jakewharton:butterknife:8.5.1'
apt 'com.jakewharton:butterknife-compiler:8.5.1'


案例:

Retrofit2的基本使用:

//获取一个Retrofit2对象
Retrofit Retrofit = new Retrofit.Builder()
.baseUrl(UrlConstant.BASE_URL_TEST)
.build();
//通过Retrofit实例,创建服务接口对象
ApiService apiService = Retrofit.create(ApiService.class);
//通过接口服务对象,调用接口中的方法,获取call对象
Call<ResponseBody> call = apiService.getNetData();
//通过call对象执行网络请求(同步请求execute,异步请求enqueue)
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
//获取json字符串
try {
String result = body.string();
tv_content.setText(result);
Log.i(TAG, result);
} catch (IOException e) {
e.printStackTrace();
}
}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i(TAG, "请求失败");
}
});


1、Retrofit2设置Json转换器

为Retrofit2添加json转换器;

当创建一个Retrofit实例的时候可以为其添加一个Json转换器,这样就会自动将Json格式的响应体转换为所需要的Java对象。

GsonFormat是AndroidStudio中的一个插件。

创建retrofit实例,我们通过addConverterFactory指定一个factory来对响应反序列化

//进行一系列的序列化设置
ObjectMapper mapper = new ObjectMapper();
//创建Retrofit实例:addConverterFactory(JacksonConverterFactory.create(mapper))
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConstant.BASE_URL2)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<LoginEntity> call = apiService.addJsonConvertFactoryTest(map);
call.enqueue(new Callback<LoginEntity>() {
@Override
public void onResponse(Call<LoginEntity> call, Response<LoginEntity> response) {
if (response.isSuccessful()) {
LoginEntity bodyList = response.body();
Log.i(TAG, bodyList.getMsg());
Log.i(TAG, bodyList.getData().getCity()+ "");
}
}
@Override
public void onFailure(Call<LoginEntity> call, Throwable t) {

}
});


2、Retrofit2手动设置网络请求客户端

可以在OkHttpClient中进行一系列的网络请求设置

OkHttpClient client = new OkHttpClient.Builder()
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConstant.BASE_URL_TEST)
.addConverterFactory(JacksonConverterFactory.create())
//手动设置OkHttpClient客户端
.client(client)
.build();


3、Retrofit2添加拦截器,获取日志信息

使用自定义的OkHttpClient

在retrofit2.0中是没有日志功能的;但是retrofit2.0中依赖OkHttp,所以也就能够通过OkHttp中的interceptor来实现获取底层的请求和响应日志;

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConstant.BASE_URL_TEST)
.addConverterFactory(JacksonConverterFactory.create())
//手动设置OkHttpClient客户端
.client(client)
.build();


4、Retrofit2添加请求头

//使用@Headers注解,添加请求头信息
@Headers({
"Content-Type: application/json",
})
@FormUrlEncoded
@POST("login")
Call<LoginEntity> addJsonConvertFactoryTest(@FieldMap Map<String,String> map);


5、Retrofit2通过Https协议访问网络配置

本事上是OkHttp协议支持https协议。

6、Retrofit2设置缓存

在自定义的OkHttpClient中进行设置



ApiService接口中的代码:

package com.example.administrator.retrofit2;

import com.example.administrator.retrofit2.entity.ItemEntity;
import com.example.administrator.retrofit2.entity.LoginEntity;
import com.example.administrator.retrofit2.entity.Student;

import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import rx.Observable;

/**
* Created on 2017/5/9.
* Author:crs
* Description:ApiService 主要用于封装网络请求参数和url
*/
public interface ApiService {
//请求方式;url参数;没有请求参数;返回值类型为Call<ResponseBody>
@GET("basil2style")
Call<ResponseBody> getNetData();

//获取第一页数据,存在子url
@GET("article/page=1")
Call<ResponseBody> getPageData();

@GET("article/list/{type}?")
Call<ResponseBody> getListData(@Path("type")String type, @Query("page")int page);

//为Retrofit添加json转化器
@GET("basil2style")
Call<List<Student>> addJsonConvertFactory();

//为Retrofit添加json转化器

//使用@Headers注解,添加请求头信息
@Headers({
"Content-Type: application/json",
})
@FormUrlEncoded
@POST("login")
Call<LoginEntity> addJsonConvertFactoryTest(@FieldMap Map<String,String> map);

@GET("search/repositories")
Call<ItemEntity> queryRetrofitByGetCallMap(@QueryMap Map<String,String> map);

@GET("search/repositories")
Call<ItemEntity> queryRetrofitByGetCall(@Query("q")String owner, @Query("since")String time,
@Query("page")int page, @Query("per_page")int per_Page);

@GET("repos/{owner}/{repo}/contributors")
Observable<List<LoginEntity>> contributorsByRxJava(@Path("owner") String owner, @Path("repo") String repo);
}


借鉴此博客: http://blog.csdn.net/ljd2038/article/details/51046512
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Retrofit2 Jackson OkHttp