Retrofit网络开源库
2016-03-31 14:05
525 查看
网络开源库有很多,不过目前最为流行或者用到最多有三个volley、okhttp、retrofit不过博主个人感觉xutil也挺好的(具体用法我会在微信中推广) 废话不多说先上源码 源码链接 点击打开链接 github上的源码 点击打开链接 简单介绍 Retrofit和okhttp是由同一个人开放的已经被谷歌所认证,若项目中存有okhttp时,Retrofit会默认使用okhttp进行网络的请求。Retrofit可以进行处理 处理GET和POST常用的请求外还可以处理PUT、DELETE等网络请求,通过注释的方式来进行把HTTP请求转换成java的接口。 集成到Retrofit到项目 集成Retrofit到项目中是通过在gradle脚本中添加
<span style="font-family:Microsoft YaHei;font-size:14px;color:#333333;"> compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'</span>导入第二个的目的是为了将请求返回的json对象转换成model 请求API注解成接口 既然要获取json数据我们就按照github上的网址来进行获取json,当然其中的fanloveoupao你可以换成自己的github账号
<span style="font-size:18px;"> https://api.github.com/users/fanloveoupao</span>[/code] Json数据模式{ "login": "fanloveoupao", "id": 15713500, "avatar_url": "https://avatars.githubusercontent.com/u/15713500?v=3", "gravatar_id": "", "url": "https://api.github.com/users/fanloveoupao", "html_url": "https://github.com/fanloveoupao", "followers_url": "https://api.github.com/users/fanloveoupao/followers", "following_url": "https://api.github.com/users/fanloveoupao/following{/other_user}", "gists_url": "https://api.github.com/users/fanloveoupao/gists{/gist_id}", "starred_url": "https://api.github.com/users/fanloveoupao/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/fanloveoupao/subscriptions", "organizations_url": "https://api.github.com/users/fanloveoupao/orgs", "repos_url": "https://api.github.com/users/fanloveoupao/repos", "events_url": "https://api.github.com/users/fanloveoupao/events{/privacy}", "received_events_url": "https://api.github.com/users/fanloveoupao/received_events", "type": "User", "site_admin": false, "name": null, "company": null, "blog": null, "location": null, "email": null, "hireable": null, "bio": null, "public_repos": 27, "public_gists": 0, "followers": 0, "following": 0, "created_at": "2015-11-08T09:43:40Z", "updated_at": "2016-03-31T05:45:12Z" }在构建对应的数据对象model时我推荐一款AndroidStudio的插件,使用快捷方便GsonFormat
这个插件将model的生成自动化了 是不是快捷方便了好多。 言归正传,现在介绍将http api转化成Java接口 首先定义接口public interface GetRetrofit { //https://api.github.com/users/fanloveoupao //进行拼接型的get请求 @GET("/users/{user}") Call<GetModel> getFreed(@Path("user") String user); }</pre><div>把请求体封装成方法</div><div><pre name="code" class="java">/** * 这里我们使用@GET注解进行get请求,@GET("str");表示这里的 * 请求地址是baseurl+str,{user}这里的user将会被方法getFreed里面的string所替代最后拼接成 * 最终的请求路径 */ @GET("users/{user}") public Call<GetModel> getSingle(@Path("user") String user);个人推荐把注解的请求体定义成方法这个,因为一个项目中的请求体不止一个,不可能一个请求定义一个接入这样不但工作量大而且还不容易维护。执行请求public void getPath(View view) { //执行请求 Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()).build(); GetRetrofit getRetrofit = retrofit.create(GetRetrofit.class); Call<GetModel> modelCall = getRetrofit.getSingle("fanloveoupao"); // Call<GetModel> modelCall = getRetrofit.getFreed("fanloveoupao"); modelCall.enqueue(new Callback<GetModel>() { @Override public void onResponse(Response<GetModel> response, Retrofit retrofit) { Log.i("TAG", "40行" + response.body().getLogin()); } @Override public void onFailure(Throwable t) { } });这里先构建Retrofit的对象注意别把包导错了,因为要把返回的json数据转换成Model对象所以加入了GsonConverterFactort进行过转换 最后利用http中的接口生成Call对象,然后进行调用enqueue队列进行执行。最后别忘记添加网络的权限,不然执行不了。 这里的拼接只是请求的路径比较段的时候,如果请求的路径比较长呢?比如下面这个http://write.blog.csdn.net/postedit?ref=toolbar&ticket=ST-162678-dlniBZKaPKcmHbhEygKY-passport.csdn.net[/code] 这里我们引入键值对,或者说另外一种注解@Query、@QueryMap 请求的参数过长时,但只有一个键值对时@GET("/home") public Call<GetModel> getLong(@Query("t") String value);这里拼接出的url就是https://api.github.com/users/home?t=value 很长的路径多个键值对时://更长时可以考虑 @GET("/home") public Call<GetModel> getMany(@QueryMap Map<String, String> optiom);多个拼接,拥有多个键值对时https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=1212120055多个键值对拼接到路径中Map<String,String> a=new HashMap<>() a.put("t","home/index"); a.put("lang","zh_CN"); a.put("oken","1212120055");我们知道常用的请求除了GET更多的是用POST,GET和POST的其中一个区别就是参数的位置,GET是把参数放进路径中而POST是放进请求体中的 按照这个不同我们来进行分析关于POST的请求@FormUrlEncoded //post请求一定要加这个 @POST("/login") public Call<GetModel> login(@Field("username") String user,@Field("password") String pass);执行请求的方式和上面GET的执行是一样的这里不做太多解释。Retrofit可以将HTTP的API请求转化成Java接口对象那么,这里就讲解一下他的其他注解方式(出现过的) 配置body的post中<span style="font-family:Microsoft YaHei;">@FormUrlEncoded @POST("/index.php") public Call<GetModel> postBody(@Body GetModel getModel);</span>还有一点需要特别注意的是在POST请求前一定要加@FormUrlEncoded。 配置请求头/** * 关于配置请求头的 * Http请求是存在请求头的有时我们要填写或者配置,不过一般我们用不到 * 不过还是简单的做下讲解吧 * * */@GET("/user")public Call<GetModel> getHeader(@Header("author") String autj);关于Retrofit的网络请求我知道就大致这么多了,对于Retrofit的理解我也是刚学到的如果有错误的或者不严密的定及时更改。 最后还是老套路,关注微信公众号走一走,扫描头像“激情”-“落料”! 阿里嘎多大家的支持,相信最好的自己慢慢去完善自己总有一天你会发现你的努力和积累也是可以有收获的。 ---鸡汤博主!