【有梦想的IT人】零基础学习Retrofit2-0(一)

Retrofit与Okhttp共同出自于Square公司,Retrofit就是对Okhttp做了一层封装,我们只需要通过简单的配置就能使用进行网络请求了,其主要作者是Android大神Jake Wharton。废话我就不多说了,直接上干货,来来,上车吧!

【有梦想的IT人】零基础学习Retrofit2-0(一)_第1张图片
Paste_Image.png

Retrofit2.0基本用法

1.Stuidio导入依赖

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

2.定义接口

public interface GitHubService {
  @GET("users/{user}/repos")
  Call> listRepos(@Path("user") String user);
}

3.获取实例

Retrofit retrofit = new Retrofit.Builder()
    //设置OKHttpClient,如果不设置会提供一个默认的
    .client(new OkHttpClient())
    //设置baseUrl
    .baseUrl("https://api.github.com/")
    //添加Gson转换器
    .addConverterFactory(GsonConverterFactory.create())
    .build();
GitHubService service = retrofit.create(GitHubService.class);

4.请求数据

  • 同步请求
Call> call = service.listRepos("octocat");
try {
     Response> repos  = call.execute();
     } catch (IOException e) {
     e.printStackTrace();
}
//call只能调用一次。否则会抛 IllegalStateException
Call> clone = call.clone();
  • 异步请求
clone.enqueue(new Callback>() {
        @Override
        public void onResponse(Call> call, Response> response) {
            // Get result bean from response.body()
            List repos = response.body();
            // Get header item from response
            String links = response.headers().get("Link");
            /**
              * 不同于retrofit1 可以同时操作序列化数据javabean和header
              */
        }

        @Override
        public void onFailure(Call> call, Throwable t) {

        }
    });

// 取消
call.cancel();

基本用法就完事了,就是这么简单!惊不惊喜?意不意外?

【有梦想的IT人】零基础学习Retrofit2-0(一)_第2张图片
Paste_Image.png
下面稍微说明一下相关注意的要点:
  • retrofit注解:

  • 方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP。

  • 标记注解,包含@FormUrlEncoded、@Multipart、@Streaming。

  • 参数注解,包含@Path,@Query,@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap。

  • 其他注解@Url:一般用于完整的url
    @HTTP:可以替代其他方法的任意一

     * method 表示请的方法,不区分大小写
     * path表示路径
     * hasBody表示是否有请求体
     */
   @HTTP(method = "get", path = "users/{user}", hasBody = false)
    Call getFirstBlog(@Path("user") String user);

@Url:使用全路径复写baseUrl,适用于非统一baseUrl的场景。

@GET
Call v3(@Url String url);

@Streaming:用于下载大文件

@Streaming
@GET
Call downloadFileWithDynamicUrlAsync(@Url String fileUrl);
ResponseBody body = response.body();
long fileSize = body.contentLength();
InputStream inputStream = body.byteStream();

@Path:URL占位符,用于替换和动态更新,相应的参数必须使用相同的字符串被@Path进行注释

@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId);
//--> http://baseurl/group/groupId/users
//等同于:
@GET
Call> groupListUrl(
      @Url String url);

@Query,@QueryMap:查询参数,用于GET查询,需要注意的是@QueryMap可以约定是否需要encode

@GET("group/users")
Call> groupList(@Query("id") int groupId);
//--> http://baseurl/group/users?id=groupId
Call> getNews((@QueryMap(encoded=true) Map options);

@Body:用于POST请求体,将实例对象根据转换方式转换为对应的json字符串参数,这个转化方式是GsonConverterFactory定义的。

 @POST("add")
 Call> addUser(@Body User user);

@Field,@FieldMap:Post方式传递简单的键值对,需要添加@FormUrlEncoded表示表单提交
Content-Type:application/x-www-form-urlencoded

@FormUrlEncoded
@POST("user/edit")
Call updateUser(@Field("first_name") String first, @Field("last_name") String last);

@Part,@PartMap:用于POST文件上传
其中@Part MultipartBody.Part代表文件,@Part("key") RequestBody代表参数
需要添加@Multipart表示支持文件上传的表单,Content-Type: multipart/form-data

 @Multipart
    @POST("upload")
    Call upload(@Part("description") RequestBody description,
                              @Part MultipartBody.Part file);
    // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
    // use the FileUtils to get the actual file by uri
    File file = FileUtils.getFile(this, fileUri);

    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

    // add another part within the multipart request
    String descriptionString = "hello, this is description speaking";
    RequestBody description =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), descriptionString);

@Header:header处理,不能被互相覆盖,用于修饰参数,

//动态设置Header值
@GET("user")
Call getUser(@Header("Authorization") String authorization)
等同于 :
//静态设置Header值
@Headers("Authorization: authorization")//这里authorization就是上面方法里传进来变量的值
@GET("widget/list")
Call getUser()

@Headers 用于修饰方法,用于设置多个Header值:

@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call getUser(@Path("username") String username);

好了关于Retrofit的用法今天就介绍到这里,我们下篇继续约,不见不散

【有梦想的IT人】零基础学习Retrofit2-0(一)_第3张图片
Paste_Image.png

你可能感兴趣的:(【有梦想的IT人】零基础学习Retrofit2-0(一))