Retrofit2网络框架的使用(一)

来源:互联网 发布:南方报业招聘网络编辑 编辑:程序博客网 时间:2024/06/05 02:32

Retrofit是Square公司研究开发的网络请求框架,它是基于okhttp实现的。废话不多说,现在就介绍下retrofit的使用方法。
首先呢,它是一个第三方库,我们需要导入它的依赖库,即在我们gradle文件下的dependencies中导入我们的依赖库,如下所示:

    //Retrofit网络请求框架    compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'

由于现在的项目中都有图片的展示,下面我需要引用到的依赖库依然还是Square公司推出的picasso这个图片下载和缓存的第三方库:

compile 'com.squareup.picasso:picasso:2.3.2'

准备工作做完了,下面开始我们今天的主题,它的使用方法。
首先我们需要创建一个业务请求接口,在这之前我们先来讲解下他在接口中用到的一些注解的含义:
1.@Query、@QueryMap
用于get请求传递参数,如下:

@GET("jsonstudy/list.do")Call<Data> getData(@Query("page") int page,@Query("rows") int rows);

他就等同于:

 @GET("jsonstudy/list.do?page=page&rows=rows")    Call<Data> getData();

就是把@Query的key-value添加到url后面组成get方式的参数,@QueryMap同理。

2.@Field
用于post请求传递参数,需要在请求接口方法上添加@FormUrlEncoded,即以表单的方式传递参数,如下:

 //post传值是动态的运行的    @POST("user/login.do?")    @FormUrlEncoded    Call<LoginResult> getData(@Field("userName") String name, @Field("passWord") String pw);

3.@Body
用于post请求,它是根据转换方式将实例对象转化为对应字符串传递参数.比如Retrofit添加GsonConverterFactory则是将body转化为gson字符串进行传递.

4.@Path
用于URL上的占位符,如下所示:

@GET("user/{id}/login.do?")Call<LoginResult> getData(@Path("id") int id);

意思也就是将id变量的值替换到url上的id位置,Path可以用于任何请求方式,包括Post,Put,Delete等等

5.@Part
配合@Multipart使用,一般用于文件上传:

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

以上就是一些基本的注解的释义。

下面开始上代码,讲解详细用法:
(1)创建Retrofit的实例

Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://192.168.0.108:8080/JsonStudy/")                .addConverterFactory(GsonConverterFactory.create())                .build();

(2)创建接口

interface ApiManager {    @GET("jsonstudy/list.do?page=1&rows=18")    Call<Data> getData();     //post传值是动态的运行的    @POST("user/login.do?")    @FormUrlEncoded    Call<LoginResult> getData(@Field("userName") String name, @Field("passWord") String pw);}

(3)异步请求这个接口(接着创建Retrofit的实例往下写)

ApiManager apiService = retrofit.create(ApiManager.class);        Call<LoginResult> call = apiService.getData("xiaoming", "1234");        call.enqueue(new Callback<LoginResult>() {            @Override            public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {                Log.e("===", "执行了:" + response.raw());                if (response.body().getCurrentUser() != null                        && response.body().getCurrentUser().size() > 0                        && response.body().getCode().equals("000")) {                    LoginResult.CurrentUserBean bean = response.body().getCurrentUser().get(0);                    Log.e("===", "bean:" + bean.getUserName());                    text_go.setText(bean.getUserName());                    Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();                }else {                    Toast.makeText(MainActivity.this,"用户不存在",Toast.LENGTH_SHORT).show();                }            }            @Override            public void onFailure(Call<LoginResult> call, Throwable t) {                Log.e("===", "请求失败:" + call.request().url());            }        });

以上就是我写的一个简单的登录的操作。

到这里Retrofit的基本使用已经讲完了,这个新的框架也是最近刚学,可能还存在一些问题,欢迎大家指正。

0 0