Retrofit的使用详解(一)

1.Retrofit的介绍

   Retrofit是一种网络请求框架,出自Square公司android 大牛Jakewharton的大手笔,其底层封装了OkHttp的框架,将网络请求的任务全权交给了OkHttp,而 我们只需 通过简单的配置,就能很好的运行Retrofit了。

2.Retrofit的各种参数的用法

1.get请求的参数解析

①@query

@GET("train/s")
Call getTrainInfo(@Query("name") String trainName, @Query("key") String key);

然后调用接口方法,传参:

Call movie= service.getTrainInfo(trainName,KEY);
是不是很简单了?

②@queryMap:跟qurey方式大同小异,只是选择map集合方式传参

Map,String> options = new HashMap,String>();
options.put("name",trainName);
options.put("key",KEY);
Call movie = service.getTrainInfo(options);
尼玛,是不是一个妈生的!

③Path:url中的占位符

@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId);
相当于动态的改变url,高大上呀,这个也so easy ! 当然别掉了{}将动态的配置参数死死的包起来,这样你就胜利了。

2.post请求的参数解析

①@FormUrlEncoded

在post请求中配置该参数,说明该请求将表单的形式传递参数,它不能用于get请求。

②@Field

@FormUrlEncoded
@POST("query")
Call postWeiInfo(@Field("key") String key);
然后调用接口方法:

Call movie = service.postWeiInfo(WX_KEY);
秒杀!!!

③@FiledMap:这个跟Field差不多

@FormUrlEncoded
@POST("voice")
Call sendVoiceMessage(@FieldMap Map,String> options);

然后在请求方法中直接通过键值对的方式添加参数。

Map,String> options = new HashMap,String>();
options.put("valicode","123456");
options.put("to","18772351259");
options.put("key",voice_KEY);
Call voice = service.sendVoiceMessage(options);

④@body:如果参数过多,统一封装到类中应该会更好,便于维护代码

@FormUrlEncoded
@POST("voice")
Call sendVoiceMessage(@Body AddParams params);

public class AddParams{
    String valicode;
    String to;
    String key;

    public void setKey(String key) {
        this.key = key;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public void setValicode(String valicode) {
        this.valicode = valicode;
    }
3.文件上传的参数解析

@Part:配合@Multipart用于文件上传

@Multipart
@PUT("user/photo")
Call updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
②上传单,多个文件

//上传单个文件
@Multipart
@POST("upload")
Call uploadFile(@Part("description") RequestBody description,
                              @Part MultipartBody.Part file);

// 上传多个文件
@Multipart
@POST("upload")
Call uploadMultipleFiles(
        @Part("description") RequestBody description,
        @Part MultipartBody.Part file1,
        @Part MultipartBody.Part file2);

③@Header:添加http header

@GET("user")
Call getUser(@Header("Authorization") String authorization);
等同于

@Headers("Authorization: authorization")//这里authorization就是上面方法里传进来变量的值
@GET("widget/list")
Call getUser()

3.Retrofit的基本使用

1.配置好Retrofit的坏境(这个需要大家注意retrofit与Okhttp版本的对应,这里我们用Retrofit 2,里面包含OkHttp,就不考虑版本的配对了)

 compile 'com.squareup.retrofit2:retrofit:2.1.0'
2.addConverterFactory(GsonConverterFactory.create()),这里使用Gson,那么还要导入:

compile 'com.squareup.retrofit2:converter-gson:2.1.0'
一定要注意版本的对应,不要报错别怪我!!!

3.通过服务器返回的json数据,创建对应的javaBean(建议用GsonFormat工具)

我这里采用了聚合数据的微信精选的Ip:http://v.juhe.cn/weixin/

public class WeiXin implements Serializable {

    /**
     * reason : success
     * result : {"list":[{"id":"wechat_20150401071581","title":"号外:集宁到乌兰花的班车出事了!!!!!","source":"内蒙那点事儿","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214279.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071581"},{"id":"wechat_20150402028462","title":"【夜读】梁晓声:你追求的,就是你人生的意义","source":"人民日报","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214521.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402028462"},{"id":"wechat_20150401071583","title":"孩子们喜欢怎样的房间 你不能装作不知道","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214277.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071583"},{"id":"wechat_20150401070488","title":"国家电网员工竟然这样办婚礼\u2026\u2026","source":"国网江苏省电力公司","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214267.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401070488"},{"id":"wechat_20150401070491","title":"【独家】2015年室内色彩搭配指南","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214270.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401070491"},{"id":"wechat_20150401070489","title":"德国人的严谨出了名 那家具设计呢?","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214269.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401070489"},{"id":"wechat_20150402003213","title":"关于家具,80%的人想这样","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214343.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003213"},{"id":"wechat_20150402004584","title":"是夫妻就要戒了这些!","source":"我是个妈妈","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214375.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402004584"},{"id":"wechat_20150402007350","title":"今天吃点后悔药 开始巅峰人生吧","source":"冷笑话精选","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214476.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402007350"},{"id":"wechat_20150402007351","title":"男生在恋爱中要明白的道理 vs 女生要明白的道理","source":"冷笑话精选","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214479.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402007351"},{"id":"wechat_20150402003473","title":"两张照片,震撼了全世界","source":"视觉志","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214358.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003473"},{"id":"wechat_20150402007349","title":"其实交对了损友,愚人节每天都过~尼玛笑哭了!","source":"冷笑话","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214475.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402007349"},{"id":"wechat_20150402004585","title":"探班颜值最高剧组\u2014\u2014《栀子花开》!","source":"快乐大本营","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214373.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402004585"},{"id":"wechat_20150401066945","title":"这个放到你的朋友圈上,大家都会感激你的!","source":"金立关怀","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214253.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401066945"},{"id":"wechat_20150401066341","title":"愚人节:你被这些谣言愚弄过吗?","source":"国网江苏省电力公司","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214250.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401066341"},{"id":"wechat_20150402004583","title":"你见过最美好的女生是什么样的","source":"清华南都","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214374.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402004583"},{"id":"wechat_20150401071587","title":" 轻松二刻 | 真的要被这些小屁孩蠢哭了!哈哈哈哈","source":"卡娃微卡","firstImg":"","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071587"},{"id":"wechat_20150402001258","title":" 生活百科 | 你的便便能告诉你。。。","source":"卡娃微卡","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214308.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402001258"},{"id":"wechat_20150402003470","title":"笨蛋汪才是人类的贴心小棉袄!!!","source":"冷兔","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214360.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003470"},{"id":"wechat_20150402003471","title":"首例男性生子成功,女人们开心吗?","source":"上街吧","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214359.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003471"}],"totalPage":16,"ps":20,"pno":1}
     * error_code : 0
     */

    private String reason;
    /**
     * list : [{"id":"wechat_20150401071581","title":"号外:集宁到乌兰花的班车出事了!!!!!","source":"内蒙那点事儿","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214279.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071581"},{"id":"wechat_20150402028462","title":"【夜读】梁晓声:你追求的,就是你人生的意义","source":"人民日报","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214521.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402028462"},{"id":"wechat_20150401071583","title":"孩子们喜欢怎样的房间 你不能装作不知道","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214277.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071583"},{"id":"wechat_20150401070488","title":"国家电网员工竟然这样办婚礼\u2026\u2026","source":"国网江苏省电力公司","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214267.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401070488"},{"id":"wechat_20150401070491","title":"【独家】2015年室内色彩搭配指南","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214270.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401070491"},{"id":"wechat_20150401070489","title":"德国人的严谨出了名 那家具设计呢?","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214269.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401070489"},{"id":"wechat_20150402003213","title":"关于家具,80%的人想这样","source":"尚品宅配","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214343.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003213"},{"id":"wechat_20150402004584","title":"是夫妻就要戒了这些!","source":"我是个妈妈","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214375.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402004584"},{"id":"wechat_20150402007350","title":"今天吃点后悔药 开始巅峰人生吧","source":"冷笑话精选","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214476.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402007350"},{"id":"wechat_20150402007351","title":"男生在恋爱中要明白的道理 vs 女生要明白的道理","source":"冷笑话精选","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214479.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402007351"},{"id":"wechat_20150402003473","title":"两张照片,震撼了全世界","source":"视觉志","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214358.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003473"},{"id":"wechat_20150402007349","title":"其实交对了损友,愚人节每天都过~尼玛笑哭了!","source":"冷笑话","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214475.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402007349"},{"id":"wechat_20150402004585","title":"探班颜值最高剧组\u2014\u2014《栀子花开》!","source":"快乐大本营","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214373.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402004585"},{"id":"wechat_20150401066945","title":"这个放到你的朋友圈上,大家都会感激你的!","source":"金立关怀","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214253.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401066945"},{"id":"wechat_20150401066341","title":"愚人节:你被这些谣言愚弄过吗?","source":"国网江苏省电力公司","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214250.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401066341"},{"id":"wechat_20150402004583","title":"你见过最美好的女生是什么样的","source":"清华南都","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214374.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402004583"},{"id":"wechat_20150401071587","title":" 轻松二刻 | 真的要被这些小屁孩蠢哭了!哈哈哈哈","source":"卡娃微卡","firstImg":"","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071587"},{"id":"wechat_20150402001258","title":" 生活百科 | 你的便便能告诉你。。。","source":"卡娃微卡","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214308.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402001258"},{"id":"wechat_20150402003470","title":"笨蛋汪才是人类的贴心小棉袄!!!","source":"冷兔","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214360.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003470"},{"id":"wechat_20150402003471","title":"首例男性生子成功,女人们开心吗?","source":"上街吧","firstImg":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-214359.jpg/168","mark":"","url":"http://v.juhe.cn/weixin/redirect?wid=wechat_20150402003471"}]
     * totalPage : 16
     * ps : 20
     * pno : 1
     */

    private ResultBean result;
    private int error_code;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public ResultBean getResult() {
        return result;
    }

    public void setResult(ResultBean result) {
        this.result = result;
    }

    public int getError_code() {
        return error_code;
    }

    public void setError_code(int error_code) {
        this.error_code = error_code;
    }

    public static class ResultBean {
        private int totalPage;
        private int ps;
        private int pno;
        /**
         * id : wechat_20150401071581
         * title : 号外:集宁到乌兰花的班车出事了!!!!!
         * source : 内蒙那点事儿
         * firstImg : http://zxpic.gtimg.com/infonew/0/wechat_pics_-214279.jpg/168
         * mark :
         * url : http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071581
         */

        private List list;

        public int getTotalPage() {
            return totalPage;
        }

        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }

        public int getPs() {
            return ps;
        }

        public void setPs(int ps) {
            this.ps = ps;
        }

        public int getPno() {
            return pno;
        }

        public void setPno(int pno) {
            this.pno = pno;
        }

        public List getList() {
            return list;
        }

        public void setList(List list) {
            this.list = list;
        }

        public static class ListBean {
            private String id;
            private String title;
            private String source;
            private String firstImg;
            private String mark;
            private String url;

            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public String getSource() {
                return source;
            }

            public void setSource(String source) {
                this.source = source;
            }

            public String getFirstImg() {
                return firstImg;
            }

            public void setFirstImg(String firstImg) {
                this.firstImg = firstImg;
            }

            public String getMark() {
                return mark;
            }

            public void setMark(String mark) {
                this.mark = mark;
            }

            public String getUrl() {
                return url;
            }

            public void setUrl(String url) {
                this.url = url;
            }
        }
    }
}
4. 创建APISercie接口类

public interface PostService {

    @POST("query")
    @FormUrlEncoded
    Call postWeiInfo(@Field("key") String key);
}
这里,我采用post请求,另外还有一个巨坑就是,你在选取请求数据的方式时,一定看清AP接口文档,文档中只有get方式的话,你就不要别出心裁的用post,做老实人最好!文档中有两种请求方式,那么随便选择一种吧

Retrofit的使用详解(一)_第1张图片

再说一次别掉坑!!!!

5. 创建一个Retrofit对象

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
这里的BaseUrl是你自己根据自己的请求ip截取的基本ip,我这里是: http://v.juhe.cn/weixin/

6.通过接口类将json数据转化成javaBean

       PostService service = retrofit.create(PostService.class);
        Call movie = service.postWeiInfo(WX_KEY);
7.最后就是执行请求了

①同步请求:

 try {
            Call weixin = (Call) movie.execute().body();
        } catch (IOException e) {
            e.printStackTrace();
        }

②异步请求(我采用的是异步请求):

movie.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                String tilte = response.body().getResult().getList().get(0).getTitle();
                textView.setText(tilte);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
               textView.setText(t.getMessage());
            }
        });
Ok,好了,大功告成了,Retrofit就请求完了,效果图:

Retrofit的使用详解(一)_第2张图片

 这次源码就不上传了,下次将Rx java结合后再上传哈!我是张星,欢迎关注!


你可能感兴趣的:(android)