Retrofit的学习

现在网上流行的网络框架Retrofit很受欢迎,但之前一直没时间学习和使用,现在就好好学习一下。
首先在在Github搜索Retrofit找到项目:这里提供一个地址:
https://github.com/caichengan/retrofit

Android studio集成Retrofit参考上面地址配置Gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'

注意:配置Grade的时候需要添加转换器,不然会获取数据出错

 compile 'com.squareup.retrofit2:converter-gson:2.3.0'

需要了解更多的点击它的 the website

现在我们先来学习快速基本使用Retrofit:

  • 首先定义一个访问网络获取数据接口:
public interface Api {
    @GET("content/list.from")
   Call getUserInfo();
}
User是存储JSOn数据的javaBean实体
  • 接着在代码中正式使用Retrofit创建实体
 Retrofit retrofit=new Retrofit.Builder(). addConverterFactory(GsonConverterFactory.create()).
 baseUrl("http://japi.juhe.cn/joke/").build();
 Api api=retrofit.create(Api.class);

//addConverterFactory(GsonConverterFactory.create())配置GSON格式转换器
  • 定义一个方法getApiResponse()获取数据并处理数据
public void getApiResponse(){
        Call userInfo = api.getUserInfo();
        userInfo.enqueue(new Callback() {
      //enqueue方法已经在主线程使用
            @Override
            public void onResponse(Call call, Response response) {
                Toast.makeText(MainActivity.this, ""+response.body().getResult().toString(), Toast.LENGTH_SHORT).show();
        //在这里对数据进行处理,此方法已经在主线程中调用。
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

自此,用Retrofit使用GET方式请求网络数据已访问成功,使用POST方式同理。不懂的可以参考Retrofit的 the website或者查看源码

现在来学习一下GET请求方式需要传递参数需要怎么处理?
  • 可以直接在URL中加入参数
  //在Api接口中定义方法
 @GET("users/list?sort=desc")
 Call getUserInfo();
  • 可以使用Querry来标识参数
@GET("content/list.from")
Call getUserInfos(@Query("id") int id);

//调用时直接方法中传递一个int类型的数据

  • 最常用的是(推荐使用)
    可以使用替换块和方法上的参数动态更新请求URL。替换块是由{参数}包围的字母数字字符串。使用相同的字符串,必须用@ path标注相应的参数。
 //在Api接口中定义方法
@GET("content/list.from/{id}")
Call getUserInfowithPath(@Path("id") int id);
  • 也可以传递集合Map的参数
//在Api接口中定义方法
@GET("content/list.from")
Call getUserInfowithMap(@QueryMap Map mapParams);

//使用时

   Map map=new HashMap<>();
   map.put("id","3");
   map.put("name","xiaoma");
  api.getUserInfowithMap(map).enqueue()
这样就可以正常使用Map集合传递参数获取数据
现在来学习一下Post请求方式需要传递参数需要怎么处理?
  • post请求
//在Api接口中定义方法
@POST("content/list.from")
Call postUserInfo(@Body User user);//User 参数实体

BaseResult获取数据存储的java实体对象

使用post请求网络数据,参数传入得是一个对象,通过构造函数new User(3)

 api.postUserInfo(new User(3)).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
            //在这里进行数据的处理显示
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
            }
        });
  • 可以通过表单形式发送参数
    方法还可以声明为发送表单编码和多部分数据。 当@ formurlen编码出现在方法上时,将发送表单编码的数据。每个键值对都使用@字段注释,其中包含名称和提供值的对象
在API中定义方法
    @FormUrlEncoded
    @POST("content/list.from")
    Call fromUserInfo(@Field("id") int id,@Field("name") String name);
   //在代码中使用方法获取数据
    api.fromUserInfo(2,"xiaowang").enqueue();
  • 在方法中使用多部分请求,部分声明使用@ part注释,可以传递文件,文本,图像等
  @Multipart
  @PUT("user/photo")
  Call updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody 
 description);
  • 可以使用@ header注释为方法设置静态标头,添加一些验证信息在头里面
@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call getUser(@Path("username") String username);
这章节只是简单了解Retrofit的使用,请求网络的几种方式。需要更深了解的自行Google学习。

你可能感兴趣的:(Retrofit的学习)