网络请求框架 Retrofit 2 工具类简单封装
1. 添加依赖
创建一个新的工程后,在你的 build.gradle 文件里面添加以下依赖。这些依赖包括 RecyclerView,Retrofit 库,还有 Google 出品的将 JSON 装换为 POJO(简单 Java 对象)的 Gson 库,以及 Retrofit 的 Gson。
compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
2. 添加网络权限
要执行网络操作,我们需要在应用的清单文件 AndroidManifest.xml 里面声明网络权限。<uses-permission android:name="android.permission.INTERNET" />
3. 创建 Retrofit 实例
import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
4.创建 API 接口
创建一个GitHubService接口,这个接口包含了我们将会用到用于执行网络请求的方法,比如 GET, POST, PUT, PATCH, 以及 DELETE。在该教程里面,我们将执行一个 GET 请求。
public interface GitHubService {
@GET("money_index")用这个接口的时候需要传一个给"shop_id"服务器Call<JK_SJZJ_Bean> getJK_SJZJ_Bean(@Query("shop_id") int shop_id);
}
5.创建 API 工具类
现在我们要新建一个工具类。我们命名为 ApiUtils。该类设置了一个 base URL 常量,
并且通过静态方法 getGitHubService() 为应用提供GitHubService接口。
public class ApiUtils {
这句话是服务器地址,这里随便写的 public static final String SERVER_ROOT_URL = "http://www.baidu.cn/"; public static GitHubService getGitHubService() { return RetrofitClient.getClient(SERVER_ROOT_URL).create(GitHubService.class); } }
6.执行请求
要在执行请求前执行这句话,这句话意思就是用它的API工具类定义的服务期地址GitHubService gitHubService = ApiUtils.getGitHubService();
public void Retrofit() {
用上边定义的API接口类来拿它的URL,并且把服务器需要的参数传给它gitHubService .getJK_SJZJ_Bean(6).enqueue(new Callback<SOAnswersResponse>() {@Override public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) { JK_SJZJ_Bean body = response.body();
Log.d("MainActivity", body);} @Override public void onFailure(Call<SOAnswersResponse> call, Throwable t) { showErrorMessage(); Log.d("MainActivity", "error loading from API"); } }); }
总结
在该教程里,已经了解了简单使用 Retrofit 的方法。