之前项目的网络请求框架用的是OkHttp,然后用的封装框架是OkhttpUtils,今天来学习一下retrofit网络请求框架,因为它经常和rxjava配合起来使用
官网地址:https://github.com/square/retrofit
项目添加依赖:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
Retrofit支持多种解析方式
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
介绍
Retrofit将HTTP API转换为Java接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
本Retrofit类生成的实现GitHubService接口
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
每个Call从创建的GitHubService可以向远程Web服务器发出同步或异步HTTP请求
Call <List <Repo >> repos = service.listRepos(“octocat”);
使用注释描述HTTP请求:
URL参数替换和查询参数支持
对象转换为请求体(例如,JSON,协议缓冲区)
多部分请求正文和文件上传
API声明
接口方法及其参数的注释指示如何处理请求。
请求方法
每个方法必须具有提供请求方法和相对URL的HTTP注释。有五个内置注释:GET,POST,PUT,DELETE,和HEAD。资源的相对URL在注释中指定。
@GET(“users / list”)
您还可以在URL中指定查询参数。
@GET(“users / list?sort = desc”)
URL操作
可以使用替换块和方法上的参数动态更新请求URL。替换块是由{和包围的字母数字字符串}。相应的参数必须@Path使用相同的字符串注释。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
也可以添加查询参数。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
对于复杂查询参数组合成一个 Map可以使用。
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
请求正文
可以指定一个对象用作具有注释的HTTP请求主体@Body
对象也将使用Retrofit实例上指定的转换器进行转换。如果没有添加转换器,只能RequestBody使用。
@POST("users/new")
Call<User> createUser(@Body User user);
表单编码和分组
方法也可以声明为发送表单编码和多部分数据。
当@FormUrlEncoded存在于方法上时,发送表单编码的数据。每个键值对都注释有@Field包含名称和提供值的对象。
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
当@Multipart方法上存在多部分请求时,使用多部分请求。使用@Part注释声明零件。
多部分使用其中一个Retrofit转换器,或者它们可以实现RequestBody来处理自己的序列化。
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
标题操作
您可以使用@Headers注释为方法设置静态头
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
请注意,标头不会相互覆盖。具有相同名称的所有标头将包含在请求中。
可以使用@Header注释动态更新请求标头。必须提供相应的参数@Header。如果值为null,则将省略标题。否则,toString将调用该值,并使用结果。
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
需要添加到每个请求的标头可以使用OkHttp拦截器指定。
同步与异步
Call实例可以同步或异步执行。每个实例只能使用一次,但调用clone()将创建一个可以使用的新实例。
在Android上,回调将在主线程上执行。在JVM上,回调将发生在执行HTTP请求的同一线程上。
改装配置
Retrofit是通过其将您的API接口转换为可调用对象的类。默认情况下,Retrofit将为您的平台提供正常默认值,但它允许自定义。
转换器
默认情况下,Retrofit只能将HTTP主体反序列化为OkHttp的ResponseBody类型,它只能接受其RequestBody类型@Body。
可以添加转换器以支持其他类型。六个同级模块适应流行的序列化库为您方便。
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
这里有一个使用GsonConverterFactory类生成接口实现的GitHubService例子,它使用Gson进行反序列化
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
自定义转换器
如果您需要与使用Retrofit不支持开箱即用的内容格式(例如YAML,txt,自定义格式)的API进行通信,或者希望使用其他库来实现现有格式,则可以轻松创建你自己的转换器。创建一个类来扩展Converter.Factory类并在构建适配器时传递实例
new Retrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(MyConverterFactory.create())
.build()
.create(JokeService.class)
.listJokes(1+"")
.enqueue(new Callback<ArrayList<JokeBean>>() {
@Override
public void onResponse(Call<ArrayList<JokeBean>> call, Response<ArrayList<JokeBean>> response) {
}
@Override
public void onFailure(Call<ArrayList<JokeBean>> call, Throwable t) {
}
});
//分开写
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://apis.baidu.com/")
.addConverterFactory(MyConverterFactory.create())
.build();
//
JokeService service = retrofit.create(JokeService.class);
//
Call<ArrayList<JokeBean>> call = service.listJokes(1 + "");
//
call.enqueue(new Callback<ArrayList<JokeBean>>() {
@Override
public void onResponse(Call<ArrayList<JokeBean>> call, Response<ArrayList<JokeBean>> response) {
Log.e("Retrofit", response.body().toString());
}
@Override
public void onFailure(Call<ArrayList<JokeBean>> call, Throwable t) {
Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//和rxjava一起使用
final String BASEURL = "http://apis.baidu.com/";
new Retrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(MyConverterFactory.create())
.build()
.create(JokeService.class)
.listJokesRx(1+"")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ArrayList<JokeBean>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(ArrayList<JokeBean> jokeBeen) {
}
});
//分开写
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://apis.baidu.com/")
.addConverterFactory(MyConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
//
JokeService service = retrofit.create(JokeService.class);
//
Observable<ArrayList<JokeBean>> observable = service.listJokesRx("" + 1);
//
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<ArrayList<JokeBean>>() {
@Override
public void onCompleted() {
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(ArrayList<JokeBean> jokeBeans) {
Log.e("Retrofit", "requestRxJava:" + jokeBeans.toString());
}
});