Android Mvp+Rxjava+Retrofit实战
目录结构
build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.orhanobut:logger:1.8'
compile 'io.reactivex:rxjava:1.1.7'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
}
Rxjava+Retrofit统一Http的封装
HttpService
Retrofit的配置
public interface HttpService {
/**
* 测量多点之间的直线距离
*
* @param waypoints 需要测距的点的经纬度坐标;需传入两个或更多的点。两个点之间用 “; ”进行分割开,单个点的经纬度用“,”分隔开;例如: waypoints=118
* .77147503233,32.054128923368;116.3521416286, 39.965780080447;116
* .28215586757,39.965780080447
* @param ak
* @param output
* @return
*/
@FormUrlEncoded
@POST("distance?")
Observable<BaseHttpResult<List<String>>> getDistance(@Field("waypoints") String waypoints,
@Field("ak") String ak,
@Field("output") String output);
}
HttpUtil
Retrofit和Rxjava进行结合 封装网络请求类
public class HttpUtil {
/**
* 超时时间
*/
private static final int DEFAULT_TIMEOUT = 10;
/**
* retrofit
*/
private Retrofit retrofit;
/**
* 接口请求
*/
private HttpService httpService;
public HttpService getHttpService() {
return httpService;
}
private HttpUtil() {
//创建一个OkHttpClient并设置超时时间
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//添加迭代器
httpClientBuilder.addInterceptor(new LoggerInterceptor());
retrofit = new Retrofit.Builder()
.client(httpClientBuilder.build())