现在市面上已经有了很多关于Retrofit的使用教程的博文,本篇只是我自己学习使用Retrofit时候的一个总结。本文参考自:霍丙乾 腾讯Bugly的《深入浅出 Retrofit,这么牛逼的框架你们还不来看看?》一文。
附:Retrofit首页及官方教程
使用首先要导入Retrofit的依赖:
//这两个依赖库的版本必须要保持一致compile 'com.squareup.retrofit2:retrofit:2.1.0'//Retrofit依赖compile 'com.squareup.retrofit2:converter-gson:2.1.0'//Retrofit数据转换的依赖,可以直接将json转化为实体类在新建项目并建立依赖之后就可以开始使用Retrofit了。
这里使用聚合数据提供的接口来获取数据:
请求地址:http://op.juhe.cn/onebox/weather/query 请求参数:cityname=%E5%8C%97%E4%BA%AC&dtype=json&key=19f4708ebed559eac920bbaa51b24a12 请求方式:GET
package com.wei.retrofitdemo.Interface;import com.wei.retrofitdemo.javaBean.WeatherInform;import retrofit2.Call;import retrofit2.http.GET;import retrofit2.http.Query;/** * Created by WQC on 2016/7/15. */public interface WeatherService { //用于指定请求的方式 @GET("weather/query") //具体的请求回调的方法,可以使用@Query注解来添加url中的参数 Call<WeatherInform> getWeather(@Query("cityname") String cityname, @Query("dtype") String dtype, @Query("key") String key);}这里边用到了WeatherInform这个JavaBean,可以使用AS的GsonFormat将json数据转换成对应的Java类:
(因为json转成的Java类太长,放在文件中供下载查看) WeatherInform.java类下载地址
Url的配置方式有多种,而且这些方式可以混合使用,但是最好只用一种,不然会头晕的。
path 是绝对路径的形式: path = “/path”,baseUrl = “URL:http://host:port/a/b” Url = “URL:http://host:port/path”
path 是相对路径,baseUrl 是目录形式: path = “path”,baseUrl = “URL:http://host:port/a/b/” Url = “URL:http://host:port/a/b/path”
path 是相对路径,baseUrl 是文件形式: path = “path”,baseUrl = “URL:http://host:port/a/b” Url = “URL:http://host:port/a/path”
path 是完整的 Url: path = “http://host:port/aa/path“,baseUrl = “http://host:port/a/b” Url = “http://host:port/aa/path”
以本文使用的URL为例(使用的是第二种方式):
path : “weather/query” baseUrl:”http://op.juhe.cn/onebox/”
所以最终的Url就是:“http://op.juhe.cn/onebox/weather/query“
1. 异步:
mWeatherCall = mWeatherService.getWeather("北京","json","19f4708ebed559eac920bbaa51b24a12"); mWeatherCall.enqueue(new Callback<WeatherInform>() { @Override public void onResponse(Call<WeatherInform> call, Response<WeatherInform> response) { if (response != null) { WeatherInform weatherInform = response.body(); if (weatherInform != null) { Log.i(TAG, "onResponse: " + weatherInform.getReason()); } }else{ Log.i(TAG, "onResponse: response is null"); } } @Override public void onFailure(Call<WeatherInform> call, Throwable t) { Log.i(TAG, "onFailure: "); } });2. 同步
try { Response<WeatherInform> weatherInform = mWeatherCall.execute(); } catch (IOException e) { e.PRintStackTrace(); }以上就是Retrofit的简单使用方法,他使用okhttp作为底层网络请求方式,在上层进行封装,使用注解的方式来使用。Retrofit还可以配合RxJava,RxAndroid来使用,提供更加简洁的网络请求方式。
新闻热点
疑难解答