您的位置:首页 > 理论基础 > 计算机网络

Retrofit网络请求框架

2017-10-18 15:00 302 查看
  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

另一个是直接用很简单的代码完成的持久化

这篇博客也不错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android