Retrofit 探索一

来源:互联网 发布:大型网络3d手游 编辑:程序博客网 时间:2024/06/16 06:35

Retrofit是目前Android最受欢迎的Http客户端库之一,回顾最早在大学时期使用的HttpClient、HttpURLConnection、xUtils到后来的Volley,再到现在已经普通使用的Okhhtp。时光荏苒,我们一直在追求更高效、简单的网络访问库。毫无疑问,现在是Retrofit的时代了。Retrofit功能上和Volley有点相似,但是在使用上却大不相同,Retrofit更加简单,更加强大。

1.首先在Modle的build.gradle中添加Retrofit依赖
compile 'com.squareup.retrofit2:retrofit:2.3.0'
2.在清单文件中添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
3.实战

现在我们来访问这个接口https://api-m.mtime.cn/PageSubArea/HotPlayMovies.api?locationId=290这个是从github上面找来的免费接口

我们需要定义个接口

/** * Created by wj on 2017/8/22. * * https://api-m.mtime.cn/PageSubArea/HotPlayMovies.api?locationId=290 */public interface ApiService {    @GET("PageSubArea/HotPlayMovies.api")    Call<AllMovieBean> getAllMovie(@QueryMap Map<String,Object> params);}

然后创建Retrofit实例

 Retrofit retrofit = new Retrofit.Builder()                .baseUrl("https://api-m.mtime.cn/")                .addConverterFactory(GsonConverterFactory.create())                .build();

最后通过Retrofit实例拿到代理对象,传入参数

  ApiService service = retrofit.create(ApiService.class);        Map<String,Object> params=new HashMap<>();        params.put("locationId",290);        Call<AllMovieBean> call = service.getAllMovie(params);        call.enqueue(new Callback<AllMovieBean>() {            @Override            public void onResponse(Call<AllMovieBean> call, Response<AllMovieBean> response) {                AllMovieBean bean = response.body();                tv_content.setText(bean.movies.size()+"");            }            @Override            public void onFailure(Call<AllMovieBean> call, Throwable t) {            }        });