Retrofit网络请求框架

  Retrofit是 Square 公司出品的默认基于 OkHttp 封装的一套 RESTful 网络请求框架,RESTful 是目前流行的一套 api 设计的风格但并不是标准。
  Retrofit 的封装可以说是很强大,里面涉及到一堆的设计模式,可以通过注解直接配置请求。不用担心android6.0不支持httpclient方式的请求,也不用引入gson去转换数据与对象同时提供对象,同时提供对 RxJava 的支持,使用Retrofit + OkHttp + RxJava + Dagger2可以说是目前比较潮的一套框架,但是门槛较高。
  这个笔记中主要记录Retrofit网络请求框架的实现.
  官方教程猛戳
  

引入依赖

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'

设置权限

 <uses-permission android:name="android.permission.INTERNET"/>

请求的链接类似下面
http://hostname/user/login?name=name&password=password

定义接口

public interface UserService {
    @GET ("/user/login")
    Call<ResponseBody> loginUser(@Query("name") String name, @Query("password") String password);
}

实例化

public void initHttp(){
    //实例化Retrofit
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(App.BASE_URL)
            .build();
    userService = retrofit.create(UserService.class);
}

网络请求

public void initHttp(String name,String password){
    Call<ResponseBody> call = userService.loginUser(name,password);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            showProgress(false);
            try {
                Log.i("tag",response.body().string());
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            showProgress(false);
            Toast.makeText(LoginActivity.this,"failuer",Toast.LENGTH_LONG).show();
            t.printStackTrace();
        }
    });
}
logcat结果

这里写图片描述

Retrofit Api 中的注解

@Query,@QueryMap,@Field,@FieldMap,@FormUrlEncoded,@Path,@Url这七种注解是最常用的。

get方式请求静态url地址

  • 无参数

    @GET ("/user/login")
    Call<ResponseBody> F0();
    
  • 少数参数

    @GET ("/user/login")
    Call<ResponseBody> loginUser(@Query("name") String name, @Query("password") String password);
    
  • 参数较多

    @GET ("/user/login")
    Call<ResponseBody> F2(@QueryMap Map<String, String> params);
    

post方式请求静态url地址

  • 无参数

    @POST ("/user/login")
    Call<ResponseBody> F0();
    
  • 少数参数

    @FormUrlEncoded
    @POST ("/user/login")
    Call<ResponseBody> loginUser(@Field("name") String name, @Field("password") String password);
    
  • 参数较多

    @FormUrlEncoded
    @POST ("/user/login")
    Call<ResponseBody> F2(@FieldMap Map<String, String> params);
    

上面的@Query和@QueryMap / @Field和@FieldMap可以结合在一起使用。

半静态的url地址请求

@GET("users/{user}/like")
Call<List<ResponseBody>> Fun(@Path("user") String user);

动态的url地址请求

@GET
Call<ResponseBody> Fun(@Url String user);

注意:

  • @Path时,path对应的路径不能包含”/”,否则会将其转化为%2F
构建好一个Retrofit对象后可以对其添加类型转换的工厂类。
.addConverterFactory(XXX)

以下有三种转换工厂提供

  • 支持string类型

    .addConverterFactory(ScalarsConverterFactory.create())
    
  • 支持gson格式

    .addConverterFactory(GsonConverterFactory.create(customGsonInstance))
    
  • 支持observable类型

    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    

完整实力化类似如下

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
retrofit2的一些convert 依赖

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
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

混淆代码

-dontwarn javax.annotation.**
-dontwarn javax.inject.**

 # OkHttp3
-dontwarn okhttp3.logging.**
-keep class okhttp3.internal.**{*;}
-dontwarn okio.**

 # Retrofit
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions

持久化Cookie

Retrofit内部是Ok来实现的,所以可以参照Ok管理Cookie。3.0之后OKHttp是加了CookieJar和Cookie两个类的
github上有人封装好了持久化cookie
另一个是直接用很简单的代码完成的持久化

这篇博客也不错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值