Retrofit是很好用的网络请求库,还可以和RxJava一起用

官网
当然不喜欢看英文一手资料的话,
看这个啊
入门必备啊有木有
然后
然后就完了

使用流程简述
- 书写Bean主体model (根据json数据写)
也可以生成,用gsonFormat工具一键生成 - 书写API接口(此处需注意,虚拟机可能用不了接口,试试真机)
- 书写APPClient
- 使用(看代码)
AppClient
import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Path;
public class AppClient {
static Retrofit mRetrofit;
public static Retrofit retrofit() {
if (mRetrofit == null) {
mRetrofit = new Retrofit.Builder()
//基本
.baseUrl("http://www.weather.com.cn/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return mRetrofit;
}
public interface ApiStores {
@GET("adat/sk/{cityId}.html")
Call<WeatherJson> getWeather(@Path("cityId") String cityId);
}
}
调用
private void getWeather() {
AppClient.ApiStores apiStores = AppClient.retrofit().create(AppClient.ApiStores.class);
Call<WeatherJson> call = apiStores.getWeather("101010100");
call.enqueue(new Callback<WeatherJson>() {
@Override
public void onResponse(Response<WeatherJson> response) {
Log.e("wxl", "getWeatherinfo=" + response.body().getWeatherinfo().getCity());
}
@Override
public void onFailure(Throwable t) {
Log.e("wxlfailure", "错误呀");
}
});
}
参数说明:
Path类型
对于
http://www.weather.com.cn/adat/sk/101010100.html
那么
.baseUrl("http://www.weather.com.cn/")
public interface ApiStores {
@GET("adat/sk/{cityId}.html")
Call<WeatherJson> getWeather(@Path("cityId") String cityId);
}
Query类型
**
* 爱卡汽车app首页请求接口
* http://a.xcar.com.cn/interface/6.0/newsList.php/*type=1&provinceId=xxx&cityId=xxx&offset=xxx&limit=xx*x&ver=xxx
*/
interface MainHttpServer{
//设置头信息 保存缓存
@Headers("Cache-Control: public, max-age=604800 ,max-stale=2419200")
// maxAge max-stale感觉两个类类似 都是设置最大失效时间,失效则不使用 需要服务器配合
//get请求
@GET("newsList.php")
Call<ArticlesModel> requestArticles(
@Query("type") String type,
@Query("provinceId") String provinceId,
@Query("cityId") String cityId,
@Query("offset") String offset,
@Query("limit") String limit,
@Query("ver") String ver
);
}
```
当然建议还是和RxJava一起用,简单暴力。。
---
end
网友评论