Retrofit2.0的简单使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dangnianmingyue_gg/article/details/62224983

1.简介

retrofit是由square公司开发的,retrofit是REST安卓客户端请求库。使用retrofit可以进行GET,POST,PUT,DELETE等请求方式。
官网参考:http://square.github.io/retrofit/

2.使用

在gradle中添加依赖

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

创建接口

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

通过接口创建实例

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

在这里baseUrl是在创建retrofit实例的时候定义的,我们也可以在API接口中定义完整的url。在这里建议在创建baseUrl中以”/”结尾,在API中不以”/”开头和结尾。

调用

Call<List<Repo>> repos = service.listRepos("octocat");

URL处理

@HTTP:可以替代其他方法的任意一种

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

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

@GET
Call<ResponseBody> getStream(@Url String url);

@Streaming:用于下载大文件

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

@Path

请求的URL可以根据函数参数动态更新。一个可替换的区块为用 { 和 } 包围的字符串,而函数参数必需用 @Path 注解表明,并且注解的参数为同样的字符串 。

GET("group/{id}/users") //注意 字符串id
List<User> groupList(@Path("id") int groupId); //注意 Path注解的参数要和前面的字符串一样 id

真实的路径是:”baseurl/group/”+groupId+”/users”

@Query/@QueryMap

@GET("group/users")
Call<List<User>> groupList(@Query("id") int groupId);

真实的路径是:”baseurl/group/users?id=groupId”
查询参数,用于GET查询,需要注意的是@QueryMap可以约定是否需要encode,如:

Call<List<News>> getNews((@QueryMap(encoded=true) Map<String, String> options);

@Body

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

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

@Field/@FieldMap

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

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

@Part/@PartMap:用于POST文件上传

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

@Multipart
@POST("upload")
Call<ResponseBody> 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);

同步请求

Call<Repo> call = service.loadRepo();
Repo repo = call.execute();

以上的代码会阻塞线程,因此你不能在安卓的主线程中调用,不然会面临NetworkOnMainThreadException。如果你想调用execute方法,请在后台线程执行。

异步请求

Call<Repo> call = service.loadRepo();
call.enqueue(new Callback<Repo>() {
    @Override
    public void onResponse(Response<Repo> response) {
        // Get result Repo from response.body()
    }

    @Override
    public void onFailure(Throwable t) {

    }
});

以上代码发起了一个在后台线程的请求并从response 的response.body()方法中获取一个结果对象。注意这里的onResponse和onFailure方法是在主线程中调用的。

取消正在进行中的业务

service 的模式变成Call的形式的原因是为了让正在进行的事务可以被取消。要做到这点,你只需调用call.cancel()。

call.cancel();

即使response存在问题onResponse依然被调用

在Retrofit 1.9中,如果获取的 response 不能背解析成定义好的对象,则会调用failure。但是在Retrofit 2.0中,不管 response 是否能被解析。onResponse总是会被调用。但是在结果不能被解析的情况下,response.body()会返回null。别忘了处理这种情况。

如果response存在什么问题,比如404什么的,onResponse也会被调用。你可以从response.errorBody().string()中获取错误信息的主体。

Retrofit支持以下的Converter

Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml

具体使用方式:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

GitHubService service = retrofit.create(GitHubService.class);

猜你喜欢

转载自blog.csdn.net/dangnianmingyue_gg/article/details/62224983