Android Retrofit之上册--入门

有空把这个也写写,希望可以帮到一些人(其实是帮我自己做点笔记)。

一、Retrofit是什么?

在回答这个问题之前,先了解一下

Retrofit就是一个Http请求库,和其它Http库最大区别在于通过大范围使用注解简化Http请求。目前Retrofit 2.0底层是依赖OkHttp实现的。

二、Retrofit 常用参数与方法
1 请求方法注解
注解 说明
@GET 表明这是get请求
@POST 表明这是post请求
@PUT 表明这是put请求
@DELETE 表明这是delete请求
@PATCH 表明这是一个patch请求,该请求是对put请求的补充,用于更新局部资源
@HEAD 表明这是一个head请求
@OPTIONS 表明这是一个option请求
@HTTP 通用注解,可以替换以上所有的注解,其拥有三个属性:method,path,hasBody
2 重点讲@post 因为公司项目用post
Api
@POST("mobile/login")
Call login(@Body LoginPost post);
@Body
public class LoginPost {
    private String username;
    private String password;

    public LoginPost(String username, String password) {
        this.username = username;
        this.password = password;
    }

}
{"password":"abc123456","username":"18611990521"}

retrofit默认采用json转化器,因此在我们发送数据的时候会将LogintPost对象映射成json数据,这样发送出的数据就是json格式的。另外,如果你不确定这种转化行为,可以强制指定retrofit使用Gson转换器:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://www.test.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();
3 @Filed & @FiledMap

@Filed通常多用于Post请求中以表单的形势上传数据,这对任何开发者来说应该都是很常见的。

@POST("mobile/register")
Call registerDevice(@Field("id") String registerid);

@FileMap和@Filed的用途相似,但是它用于不确定表单参数个数的情况下。

4 上传文件

单张图片上传
retrofit 2.0的上传和以前略有不同,需要借助@Multipart注解、@Part和MultipartBody实现。
首先定义上传接口

@Multipart
@POST("mobile/upload")
Call upload(@Part MultipartBody.Part file);

调用

File file = new File(url);
//构建requestbody
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//将resquestbody封装为MultipartBody.Part对象
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

多图上传
和单文件上传的唯一区别就是将@Part注解换成了@PartMap注解。这意味我们可以以Map的形式进行多文件上传。具体如何调用相信你已经明白。

@Multipart
@POST("upload/upload")
Call upload(@PartMap Map map);

图文混传

@Multipart
@POST("")
Call register(@Body RegisterPost post,@Part MultipartBody.Part image);
5 文件下载
@GET
Call downloadPicture(@Url String fileUrl);

代码

 InputStream is = responseBody.byteStream();
 String[] urlArr = url.split("/");
 File filesDir = Environment.getExternalStorageDirectory();
 File file = new File(filesDir, urlArr[urlArr.length - 1]);
 if (file.exists()) file.delete();

这里需要注意的是如果下载的文件较大,比如在10m以上,那么强烈建议你使用@Streaming进行注解,否则将会出现IO异常.

@Streaming
@GET
Observable downloadPicture(@Url String fileUrl);
6 @Part & @PartMap

多用于Post请求实现文件上传功能。关于这两者的具体使用参考下文的文件上传。
在这里我们来解释一下@Filed和@Part的区别。
两者都可以用于Post提交,但是最大的不同在于@Part标志上文的内容可以是富媒体形势,比如上传一张图片,上传一段音乐,即它多用于字节流传输。而@Filed则相对简单些,通常是字符串键值对。

异步VS同步

任何一个任务都可以被分为异步任务或者同步任务,和其它大多数的请求框架一样,retrofit也分为同步请求和异步请求。在retrofit是实现这两者非常简单:

同步调用

同步请求需要借助retrofit提供的execute()方法实现。

public void get() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();
        GitHubApi api = retrofit.create(GitHubApi.class);
        Call call = api.contributorsBySimpleGetCall(mUserName, mRepo);
        Response response = call.execute();
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            //处理成功请求
        }else{
            //处理失败请求
        }
    }
异步调用

异步请求需要借助retrofit提供的enqueue()方法实现。(从这个方法名中你可以看出之该方法实现的是将请求加入请求队列)。想async-http一样,同样你需要在enqueue(()方法中为其最终结果提供相应的回调,以实现结果的处理。

    public void get() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();
        GitHubApi api = retrofit.create(GitHubApi.class);

        Call call = api.contributorsBySimpleGetCall(mUserName, mRepo);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                //处理请求成功

            }

            @Override
            public void onFailure(Call call, Throwable t) {
                //处理请求失败
            }
        });
    }
7 移除请求

要想取消一个请求(无论异步还是同步),则只需要在响应的Call对象上调用其cancel()对象即可。

public void cancle(){
            Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();
        GitHubApi api = retrofit.create(GitHubApi.class);
        Call call = api.contributorsBySimpleGetCall(mUserName, mRepo);
        Response response = call.execute();
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            //处理成功请求
        }else{
            //处理失败请求
        }

        ...

//取消相关请求
call.cancel();

}
8 多次请求

个别情况下我们可能需要一个请求执行多次。但是我们在retrofit中,call对象只能被调用一次,这时候该怎么办?
这时候我们可以利用Call接口中提供的clone()方法实现多次请求。

 public void multi_async_get() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();
        GitHubApi api = retrofit.create(GitHubApi.class);
        Call call = api.contributorsBySimpleGetCall(mUserName, mRepo);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                //请求成功
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                //请求失败
            }
        });

        call.clone().enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                //请求成功
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                //请求失败
            }
        });
    }
中文乱码

虽然说,现在的项目都是使用UTF-8的编码格式,但是,在使用Retrofit的过程中,笔者发现有时候还是会出现中文乱码的问题,那么这个时候就要用到@FormUrlEncoded注解了:

public interface RXApi{

    @FormUrlEncoded // 在方法前使用注解
    @POST("url") // 有中文,当然使用@POST啦
    Call getData(@Query("var1") String var1, // 正常的@Query还是可以使用
                    @Field("var2") String var2, // 需要防止乱码的参数使用@Field注解
                    @FieldMap Map map // 如果有多个数据,可以使用@FieldMap注解
    );
}

注意:如果使用了@FormUrlEncoded注解,那么在方法的参数中至少要有一个@Field或@FieldMap注解。

设置通用请求参数

在实际项目中,各个客户端往往需要向服务端传送一些固定的参数,通常来说有两种方案:

1 可以将这个公共的请求参数放到请求Header中
2 也可以将其放在请求参数中
private void commonParamsInterceptor() {
        Interceptor commonParams = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request originRequest = chain.request();
                Request request;
//                String method = originRequest.method();
//                Headers headers = originRequest.headers();
                HttpUrl httpUrl = originRequest.url().newBuilder().addQueryParameter("paltform", "android").addQueryParameter("version", "1.0.0").build();
                request = originRequest.newBuilder().url(httpUrl).build();
                return chain.proceed(request);
            }
        };

        return commonParams;
    }
三、Retrofit的使用
1 添加依赖
dependencies {
    ...
    compile 'com.android.support:appcompat-v7:25.3.1'
    /* butterknife */
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    
    /* 响应式*/
    compile 'io.reactivex:rxjava:1.1.6'
    // RxJava
    compile 'io.reactivex:rxandroid:1.2.1'
    // RxAndroid
    /*retrofit*/
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    // 如果要是用Gson转换的话,需要添加这个依赖
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.7.0'
   
}
四、Retrofit+Rxjava

参考
急速开发系列——Retrofit实战技巧
Retrofit2.0使用总结及注意事项- BoBoMEe - 博客频道- CSDN.NET
http://blog.csdn.net/biezhihua/article/details/49232289

你可能感兴趣的:(Android Retrofit之上册--入门)