您的位置:首页 > 编程语言 > Java开发

Retrofit的简单使用方法

2016-08-26 11:53 141 查看
Retrofit是一个类型安全的网络请求库,它和OKHttp共同出自于square公司。Retrofit是对OKHttp做了一层封装,把网络请求都交给了OKHttp,简化了网络请求流程,使我们只需要通过简单的配置就能使用retrofit来进行网络请求了。下面就来看下
Retrofit
的简单使用方法:

(一) 引入库

在gralde文件中引入后续要用到的库

/**Retrofit引入库*/
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'

/**O_K_HTTP引入库*/
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'


(二) 初始化Retrofit

创建Retrofit,并设置BaseURL和Json转换,
ServiceGenerator
工具类:

/**
* 封装的Retrofit工具类
*/
public class ServiceGenerator {

/**初始化OkHttpClient*/
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS);//设置超时时间
/**初始化Retrofit*/
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://zthdwl.com/wap.php/")//baseURL
.addConverterFactory(FastJsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create());

public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build())
.build();
return retrofit.create(serviceClass);
}

}


(三) 定义接口

RequestUrl
接口类:

public interface RequestUrl {

@FormUrlEncoded
@POST("Public/loginAction")
Call<User> LoginVery(@Field("phone") String phone, @Field("password") String password, @Field("type") String type);
}


(四) 网络请求使用

创建请求服务,并为网络请求方法设置参数:

RequestUrl service = ServiceGenerator.createService(RequestUrl.class);


发送请求,通过调用Retrofit2的execute(同步)或者enqueue(异步)方法,发送请求到网络服务器,并返回一个响应(Response):

Call<User> loginCall = service.LoginVery(CodeUtils.encodeToString(account),
CodeUtils.encodeToString(password),
CodeUtils.encodeToString(type));
loginCall.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful())
{
/**请求成功*/
User user= new User();
user = response.body();
System.out.print(user);
}
}

@Override
public void onFailure(Call<User> call, Throwable t) {
/**请求失败*/
Log.e("Login Throwable",t.getMessage());
}
});


Retrofit 与 RxJava结合使用

Retrofit本身对Rxjava提供了支持。下面来看下两者结合该怎么使用:

(一) 首先要添加Retrofit对RxJava的支持,在build.gradle中添加:

compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'


(二) 在定义Retrofit时,使用RxJava作为毁掉适配器:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
//添加RxJava作为回调适配器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();


(三) 定义接口

使用Retrofit与RxJava结合,那么定义的RequestUrl 返回值就不在是一个Call了,而是一个Observable,代码如下:

public interface RequestUrl {

@FormUrlEncoded
@POST("Public/loginAction")
Observable<String> LoginVery1(@Field("phone") String phone, @Field("password") String password, @Field("type") String type);

//    @FormUrlEncoded
//    @POST("Public/loginAction")
//    Call<User> LoginVery(@Field("phone") String phone, @Field("password") String password, @Field("type") String type);

}


(四) 网络请求使用

创建请求服务,并为网络请求方法设置参数和之前的方法相同:

RequestUrl service = ServiceGenerator.createService(RequestUrl.class);


发送请求则是通过RxJava的观察者模式和订阅方法来实现:

Observable<User> stringObservable = service.LoginVery2(CodeUtils.encodeToString(account),
CodeUtils.encodeToString(password),
CodeUtils.encodeToString(type));
stringObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<User>() {
@Override
public void call(User s) {
Log.e("loginResponse1", s.toString());
User loginResponse = s;

if (loginResponse.errcode.equals("00001")) {
mLoginResponseOnListener.onSuccess(loginResponse);
} else {
mLoginResponseOnListener.onFailure(loginResponse.errinfo);
}
}
});


这样基本上就完成了Retrofit和Rxjava的简单结合。

Android开发路上一只小菜鸟的拙见,如有错误欢迎批评指出,定及时纠正,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Retrofit Rxjava