Retrofit
Retrofit是一套RESTful架构的Android(Java)客户端实现,基于注解,提供JSON to POJO(Plain Ordinary Java Object,简单Java对象),POJO to JSON,网络请求(POST,GET,PUT,DELETE等)封装。
使用方法
第一步:定义编译依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
第二步:定义接口
public interface ApiService {
@GET("service/getIpInfo.php")
Observable<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);
}
第三步:生成接口的实现类,下面通过一个工厂类的create的方法创建。第二个参数传入第二步定义的接口。
public final class RetrofitFactory {
private RetrofitFactory() {
}
public static <T> T create(String baseUrl, Class<T> clazz) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(OkHttpClientFactory.create())
.build()
.create(clazz);
}
public static <T> T create(String baseUrl, Class<T> clazz, Interceptor interceptor) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(OkHttpClientFactory.create(interceptor))
.build()
.create(clazz);
}
}
第四步:调用接口请求数据
RetrofitFactory.create(baseUrl,ApiService.class).getIpInfo("192.168.1.25");