转自:http://www.jianshu.com/p/308f3c54abdd
Retrofit是Square出品的Android Http请求框架,是基于Okhttp的(Okhttp也是该机构搞的)。Retrofit经历了从1.x版本到2.x版本,是构造REST风格的HTTP客户端的利器。
(1)定义接口
public interface BlogService {
@GET("blog/{id}")
Call getBlog(@Path("id") int id);
}
(2)获取代理实例
BlogService service = retrofit.create(BlogService.class);
Call call = service.getBlog(2);
// 用法和OkHttp的call如出一辙,
// 不同的是如果是Android系统回调方法执行在主线程
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
(4)结果输出
{"code":200,"msg":"OK","data":{"id":2,"date":"2016-04-15 03:17:50","author":"怪盗kidou","title":"Retrofit2 测试2","content":
"这里是 Retrofit2 Demo 测试服务器2"},"count":0,"page":0}
/**
* Map的key作为表单的键
*/
@POST("/form")
@FormUrlEncoded
Call testFormUrlEncoded2(@FieldMap Map map);
/**
* {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
* 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
*/
@POST("/form")
@Multipart
Call testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
作用于方法的heads
作用于形参的Header, Body, Field, FieldMap,Part,PartMap, Path, Query, QueryMap, Url
例如:
public interface BlogService {
@GET("blog/{id}") //这里的{id} 表示是一个变量
Call getBlog(/** 这里的id表示的是上面的{id} */@Path("id") int id);
}
public interface BlogService {
@GET("/headers?showAll=true")
@Headers({"CustomHeader1: customHeaderValue1", "CustomHeader2: customHeaderValue2"})
Call testHeader(@Header("CustomHeader3") String customHeaderValue3);
}
返回后按这个时间格式进行解析
Gson gson = new GsonBuilder()
//配置你的Gson
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
//可以接收自定义的Gson,当然也可以不传
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
public interface BlogService {
@POST("blog")
Call> createBlog(@Body Blog blog);
}
Gson gson = new GsonBuilder()
//配置你的Gson
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
//可以接收自定义的Gson,当然也可以不传
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
BlogService service = retrofit.create(BlogService.class);
Blog blog = new Blog();
blog.content = "新建的Blog";
blog.title = "测试";
blog.author = "怪盗kidou";
Call> call = service.createBlog(blog);
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
// 已经转换为想要的类型了
Result result = response.body();
System.out.println(result);
}
@Override
public void onFailure(Call> call, Throwable t) {
t.printStackTrace();
}
});
call.enqueue(new Callback(){});
同步
call.execute
public interface BlogService {
@POST("/blog")
Observable>> getBlogs();
}
BlogService service = retrofit.create(BlogService.class);
service.getBlogs(1)
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber>>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.err.println("onError");
}
@Override
public void onNext(Result> blogsResult) {
System.out.println(blogsResult);
}
});