[Android 知识点] 网络请求框架Retrofit使用
来源:互联网 发布:微商和淘宝的区别 编辑:程序博客网 时间:2024/09/21 09:00
- API文档:http://square.github.io/retrofit/2.x/retrofit/
- GitHub地址:https://github.com/square/retrofit
- 官方网站:http://square.github.io/retrofit/
介绍
Retrofit将Http请求转化成一个Java接口
public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user);}
Retrofit类实现GitHubService接口
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build();GitHubService service = retrofit.create(GitHubService.class);
从GitHubService 得到每一个call都会进行一次同步或异步网络请求到服务器
Call<List<Repo>> repos = service.listRepos("octocat");
用注解的方式描述Http请求
- 支持URL参数
- 实体转换,如JSON
- 多请求和文件上传
API介绍
每一个方法,必须含有一个Http注解,内置5个注解:
GET, POST, PUT, DELETE, HEAD,在注解中指定相关资源
REQUEST METHOD
@GET("users/list")
也可以指定查询参数
@GET("users/list?sort=desc")
也可以指定变参
@GET("{name}")Call<User> getUser(@Path("name") String name);
URL 操作
URL中的路劲参数需要用@Path进行注解,添加查询参数,使用@Query进行注解
@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId);
也可以添加参数
@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
也可以添加参数组合,使用Map集合
@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
REQUEST BODY
一个实体可以用@Body注解进行指定
@POST("users/new")Call<User> createUser(@Body User user)
可以使用转化器,如果没有,只能用RequestBody
FORM ENCODED AND MULTIPART
表格数据可以用 @FormUrlEncoded进行注解
@FormUrlEncoded@POST("user/edit")Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
多个请求可以用@Multipart进行注解,每一个部分可以用@Part进行注解
@Multipart@PUT("user/photo")Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
HEADER 操作
用 @Headers进行注解
@Headers("Cache-Control: max-age=640000")@GET("widget/list")Call<List<Widget>> widgetList();
@Headers({ "Accept: application/vnd.github.v3.full+json", "User-Agent: Retrofit-Sample-App"})@GET("users/{username}")Call<User> getUser(@Path("username") String username);
也可以在参数中进行注解
@GET("user")Call<User> getUser(@Header("Authorization") String authorization)
SYNCHRONOUS VS. ASYNCHRONOUS
Call实例可以同步执行,或者异步执行,但只能用一个,可以使用clone()创建新的实例。
回调函数会被执行在主线程。
- 同步使用:execute()
- 异步使用:enqueue()
mService.getAnswers().enqueue(new Callback<SOAnswersResponse>() { @Override public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) { if(response.isSuccessful()) { mAdapter.updateAnswers(response.body().getItems()); Log.d("MainActivity", "posts loaded from API"); }else { int statusCode = response.code(); // handle request errors depending on status code } } @Override public void onFailure(Call<SOAnswersResponse> call, Throwable t) { showErrorMessage(); Log.d("MainActivity", "error loading from API"); }});
其中,onResponse表示成功回调函数,onFailure表示失败回调函数。
Retrofit Configuration
实体转换
- Gson: com.squareup.retrofit2:converter-gson
- Jackson: com.squareup.retrofit2:converter-jackson
- Moshi: com.squareup.retrofit2:converter-moshi
- Protobuf: com.squareup.retrofit2:converter-protobuf
- Wire: com.squareup.retrofit2:converter-wire
- Simple XML: com.squareup.retrofit2:converter-simplexml
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
下面是一个例子:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .build();GitHubService service = retrofit.create(GitHubService.class);
也可以自定义转换器
方法:创建一个类继承 Converter.Factory class and pass in an instance when building your adapter.
依赖
GRADLE
compile ‘com.squareup.retrofit2:retrofit:2.1.0’
混淆
# Platform calls Class.forName on types which do not exist on Android to determine platform.-dontnote retrofit2.Platform# Platform used when running on RoboVM on iOS. Will not be used at runtime.-dontnote retrofit2.Platform$IOS$MainThreadExecutor# Platform used when running on Java 8 VMs. Will not be used at runtime.-dontwarn retrofit2.Platform$Java8# Retain generic type information for use by reflection by converters and adapters.-keepattributes Signature# Retain declared checked exceptions for use by a Proxy instance.-keepattributes Exceptions
案例
- 配置Gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.google.code.gson:gson:2.6.1'compile 'com.squareup.retrofit2:converter-gson:2.1.0'
- 添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
- 生成Gson实体类
可以借助工具jsonschema2pojo ,需要vpn
也可以借助AS的一个插件:Json2Pojo 进行Gson实体类的自动生成
4.自己编写一个接口
public interface xxxxxService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user);}
5.构造一个Retrofit
etrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build();GitHubService service = retrofit.create(GitHubService.class);
6.获取一个网络请求Call实例
Call<List<Repo>> repos = service.listRepos("octocat");
7.进行同步/异步调用
// 同步调用List<Repo> data = repos.execute(); // 异步调用repos.enqueue(new Callback<List<Repo>>() { @Override public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) { List<Repo> data = response.body(); } @Override public void onFailure(Call<List<Repo>> call, Throwable t) { t.printStackTrace(); } });
- [Android 知识点] 网络请求框架Retrofit使用
- Android网络请求框架Retrofit使用详解
- Android中retrofit网络请求框架使用
- Android 网络请求:Retrofit 使用
- Android 网络请求:Retrofit 使用
- Retrofit网络请求框架使用简析——Android网络请求框架(四)
- Android网络请求框架之Retrofit(一)
- Android网络请求框架之Retrofit(二)
- Android网络请求框架之Retrofit(三)
- Android高效网络请求Retrofit框架
- Android网络请求框架之Retrofit实践
- Android 网络请求框架之Rxjava+Retrofit
- Android 网络请求框架之Rxjava+Retrofit
- Android 网络请求框架之Rxjava+Retrofit
- Android 网络请求框架之Rxjava+Retrofit
- Android网络请求框架:Retrofit入门
- Retrofit 2.0 Android网络请求框架
- 网络请求框架Retrofit的基本使用
- Leetcode Reverse Linked List II
- Spring SpringMVC配置
- 8. OpenGL--混合
- 在ubuntu14.04下使用codeblocks(C++)调试caffe
- 不要QUARTZ一直输出信息
- [Android 知识点] 网络请求框架Retrofit使用
- 9. OpenGL--抗锯齿
- Javascript中"=="和"==="的区别
- 比努力更重要的是学会“简单思考”
- Unity 设置材质属性事件
- linux二进制信号量的概念
- 2016 年谷歌开源了这些超酷炫的项目
- 使用CMake编译代码教程之1
- git小分支