简介
Retrofit官方网站的介绍是 A type-safe HTTP client for Android and Java。主要用于Android和JAVA的网络访问。
使用
1.将网络请求封装在接口中
public interface GitHubService {
/*每一个方法必须有一个HTTP注解,提供请求的类型和URL
*一共有五种注解GET, POST, PUT, DELETE, HEAD
*也可以给URL加上参数 例如:@GET("/users/list?sort=desc")
*URL是子路径,在构建retrofit时会加上baseUrl
*/
@GET("/users/{user}/repos")
//Repo是Gson解析的实体类
Call<List<Repo>> listRepos(@Path("user") String user);
}
2.通过Retrofit类生成接口的实现
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
//添加Gson转换器
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
3.获取相应Http请求的Call
Call<List<Repo>> repos = service.listRepos("octocat");
4.同步或异步请求
List<Repo> repo = call.execute();//同步请求,会造成阻塞。
//异步请求
call.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Response<List<Repo>> response) {
// Get result List<Repo>from response.body()
//注意,请求失败也是调用onResponse
//可以调用response.code()获取返回码,
//或者response.isSuccess()判断请求是否成功
}
@Override
public void onFailure(Throwable t) {
}
});
URL操作
//请求URL使用替换块和参数可以动态更新方法。
//周围是一个字母数字字符串替换块 {和 }。相应的参数必须注释 @Path使用相同的字符串。
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId);
//查询参数也可以被添加
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);
//对于复杂的查询参数组合 可以使用Map
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
//还可以指定对象作为HTTP请求体
实例,使用Retrofit获取github贡献者
要访问的链接为https://api.github.com/repos/square/retrofit/contributors
这个链接返回了一大串JSON字段,我们要通过Retrofit来处理。
1.定义接口,owner,repo为可替换字段
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributer>> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
2.构造Json对应的实体类Contributor,这里就不写了,可以使用GsonFormat快速生成。
3.构建retrofit,获取Call
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHub github = retrofit.create(GitHub.class);
contributors.Call<List<Contributer>> call = github.contributors("square", "retrofit");
4.开始请求
call.enqueue(new Callback<List<Contributer>>() {
@Override
public void onResponse(retrofit.Response<List<Contributer>> response, Retrofit retrofit) {
if(response.isSuccess()){
for (Contributer c : response.body()) {
System.out.println(c.toString());
}
}
}
@Override
public void onFailure(Throwable t) {
System.out.println(t.getMessage());
}
});
其他
- 使用时在build.gradle中加入
compile 'com.google.code.gson:gson:2.3'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
- 官方还提供了其他转换器
Gson: com.squareup.retrofit:converter-gson
Jackson: com.squareup.retrofit:converter-jackson
Moshi: com.squareup.retrofit:converter-moshi
Protobuf: com.squareup.retrofit:converter-protobuf
Wire: com.squareup.retrofit:converter-wire
Simple XML: com.squareup.retrofit:converter-simplexml
- 还可以自定义转换器,比如String类型的转换器
package com.zq.myapplication;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import retrofit.Converter;
/**
* Created by zq on 2015/11/7.
*/
public class StringConverter extends Converter.Factory {
public StringConverter() {
super();
}
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
return new StringResponseBodyConverter<>();
}
@Override
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
return new StringRequestBodyConverter<>();
}
class StringResponseBodyConverter<T> implements Converter<ResponseBody, String> {
@Override
public String convert(ResponseBody value) throws IOException {
return value.string();
}
}
class StringRequestBodyConverter<T> implements Converter<String, RequestBody> {
@Override
public RequestBody convert(String value) throws IOException {
return RequestBody.create(null, value.toString());
}
}
}