网络框架之Retrofit详细讲解《一》

来源:互联网 发布:灰姑娘网络语什么意思 编辑:程序博客网 时间:2024/06/03 08:16

最近retrofit比较火,所以研究下,做下笔记,供自己以后参考下,也算是给现在的自己一个交代,等两三年后再来回顾下当初的见解和看法。

参考文档:Retrofit官方文档
Retrofit源码分析及设计模式分析

因为Retrofit的主要作用是用于网络数据的加载,所以在这里主要写一下数据解析的方法:

导包;

 compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'    compile ('com.squareup.retrofit2:converter-simplexml:2.1.0'){            exclude group:"xpp3",module:"xpp3"            exclude group:"stax",module:"stax-api"            exclude group:"stax",module:"stax"    }

接口代码:

public interface Service {    @GET("/")    Call<String> getBaidu();    @GET("/api/{category}/list")    Call<Tngou> getList(@Path("category") String category,@Query("id") int id , @Query("page") int page, @Query("rows") int rows);    //post请求的时候将属性改成Filed,加上FormUrlEncoded注解即可    @POST("/api/{category}/list")    @FormUrlEncoded    Call<Tngou> getPost(@Path("category") String category, @Field("id") int id , @Field("page") int page, @Field("rows") int rows);    @GET("/portal.php?mod=rss&catid=")    Call<Channel> getChannel();}

xml数据类对象:

@Root(strict = false)public class Channel {    @Path("channel")    @Element(name = "title")    private String title;   @ElementList(name = "title",inline = true)    private List<Item> mList;    //自己添加getter和setter
@Root(strict = false )public class Item {    @Element(name = "title")    private String title;}

Json数据类对象

public class Tngou {    @SerializedName("status")    private boolean status;    @SerializedName("total")    private int total;    @SerializedName("tngou")    private List<Cook> mList;    //自己添加getter和setter
public class Cook {    @SerializedName("id")        private int id;    @SerializedName("name")        private String name;//名称    @SerializedName("food")        private String  food;//食物    @SerializedName("img")        private String img;//图片    @SerializedName("images")        private String images;//图片,    @SerializedName("description")        private String description;//描述    @SerializedName("keywords")        private String keywords;//关键字    @SerializedName("message")        private String message;//资讯内容    @SerializedName("count")        private int count ;//访问次数    @SerializedName("fcount")        private int fcount;//收藏数    @SerializedName("rcount")        private int rcount;//评论读数        //自己添加getter和setter

大功告成,xml,json,搞定!

1 0
原创粉丝点击