Rtrofit2+Okhttp让网络请求更简单

Rtrofit与Okhttp简介

    提到Rtrofit和Okhttp就不得不说到square团队,这是一个非常优秀的团队,其团队奉献了不少优秀的开源库。目前Rtrofit和Okhttp可以说是android网络框架中的明星,其使用简便和配合解耦度高使得它们成为了android程序员们的最爱,目前使用的Rtrofit为2.0以后的版本。

Retrofit官网

Square团队的github地址


Rtrofit的使用注解(这些注解也是retrofit的核心)

1@GET GET网络请求方式
2@POST POST网络请求方式
3@Headers()头信息参数
4@Path() 路径参数,替换url地址中{ }所括的部分
5@Query() 查询参数,将在url地址中追加类似“page=1”的字符串,形成提交给服务端的请求参数
6@QueryMap查询参数集合,将在url地址中追加类似“type=text&username=abc&password=123”的字符串 
7@FormUrlEncoded对表单域中填写的内容进行编码处理,避免乱码
8@Field() 指定form表单域中每个空间的额name以及相应的数值
9@FieldMap表单域集合
10@Multipart Post提交分块请求,如果上传文件,必须指定Multipart

11@Body Post提交分块请求

注意:大部分注解都可固定或动态改变来做网络请求


Rtrofit使用详解

一、添加依赖

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.8.1'

二、构建Okhttp对象(该对象可以设置超时时间和代理模式及很多其他配置,也体现了okhttp和retrofit配合使用的优势)

OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .build();

三、初始化Retrofit对象

//获取Retrofit对象,设置地址
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://localhost")
        .client(OK_HTTP_CLIENT)
        .build();

四、初始化Rtrofit请求接口

public interface RequestServices {
            @GET  //定义返回的方法,返回的响应体使用了ResponseBody
            Call<ResponseBody> getString(@Url String url);
            @FormUrlEncoded
            @POST
            Call<ResponseBody> post(@Url String url, @FieldMap Map<String, String> params);
    }

五、构造请求体进行网络请求

(1)Get方式请求

  RequestServices requestServices = retrofit.create(RequestServices.class);//RequestServices为上一步中的Rtrofit请求接口
        Call<ResponseBody> call = requestServices.getString("http://www.baidu.com");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()){
                    try {
                        //请求成功后的回调

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                //请求失败后的回调
            }
        });

(2)Post方式请求

 RequestServices requestServices = retrofit.create(RequestServices.class);
        Map<String,String> pamars = new HashMap<>();
        pamars.put("location","成都");
        pamars.put("key","这里是我的和风天气key就不透露了");
        Call<ResponseBody> call = requestServices.post("https://free-api.heweather.com/s6/weather?parameters",pamars);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()){
                    try {
                        //请求成功后的回调
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                //请求失败后的回调
            }
        });

温馨提示:android网络请求返回结果多为Json格式,推荐使用谷歌开源库Gson来进行解析,使用较为简便。


Retrofit地址构建方法

方法一

Retrofit retrofit = Retrofit.Builder()  
    .baseUrl("https://your.api.url/");
    .build();

UserService service = retrofit.create(UserService.class);  
service.profilePicture("https://s3.amazon.com/profile-picture/path");
//请求地址则为 https://s3.amazon.com/profile-picture/path

方法二

Retrofit retrofit = Retrofit.Builder()  
    .baseUrl("https://your.api.url/");
    .build();

UserService service = retrofit.create(UserService.class);  
service.profilePicture("profile-picture/path");
// 请求地址则为 https://your.api.url/profile-picture/path

方法三

Retrofit retrofit = Retrofit.Builder()  
    .baseUrl("https://your.api.url/v2/");
    .build();

UserService service = retrofit.create(UserService.class);  
service.profilePicture("/profile-picture/path");
//请求地址则为  https://your.api.url/profile-picture/path


Retrofit注解动态或固定使用方法解释

该部分借鉴于CSDN某大神 其文章地址

Retrofit的注解机制可以说是Retrofit的核心部分,利用注解来简化代码,便于理解。


固定头

interface SomeService {
 @GET("/some/endpoint")
 @Headers("Accept-Encoding: application/json")
 Call<SomeResponse> someEndpoint();
}

someService.someEndpoint();

// GET /some/endpoint HTTP/1.1
// Accept-Encoding: application/json


动态头

interface SomeService {
 @GET("/some/endpoint")
 Call<SomeResponse> someEndpoint(
 @Header("Location") String location);
}

someService.someEndpoint("Droidcon NYC 2015");

// GET /some/endpoint HTTP/1.1
// Location: Droidcon NYC 2015


固定头+动态头

interface SomeService {
 @GET("/some/endpoint")
 @Headers("Accept-Encoding: application/json")
 Call<SomeResponse> someEndpoint(
 @Header("Location") String location);
}

someService.someEndpoint("Droidcon NYC 2015");

// GET /some/endpoint HTTP/1.1
// Accept-Encoding: application/json
// Location: Droidcon NYC 2015


无body的post请求

interface SomeService {
 @POST("/some/endpoint")
 Call<SomeResponse> someEndpoint();
}

someService.someEndpoint();

// POST /some/endpoint?fixed=query HTTP/1.1
// Content-Length: 0


有body的post请求

interface SomeService {
 @POST("/some/endpoint")
 Call<SomeResponse> someEndpoint(
 @Body SomeRequest body);
}

someService.someEndpoint();

// POST /some/endpoint HTTP/1.1
// Content-Length: 3
// Content-Type: greeting
//
// Hi!

 这里只简单列举了几个方法,其余注解使用方法大致相似,就不再列举


Retrofit优点

(1)超级解耦合

(2)使用简便

(3)配合okhttp后可满足不同使用需求

(4)支持同步和异步请求(可配合Rxjava)

(5)响应式编程模式


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值