Retrofit2.0使用

简介: 转自:http://blog.csdn.net/qq_17766199/article/details/49946429 Retrofit项目Github主页:点击打开链接 Retrofit项目官方文档   :点击打开链接 首先是我参考的文章: ● Retrofit 2.0:有史以来最大的改进 ● 使用Retrofit请求API数据

转自:http://blog.csdn.net/qq_17766199/article/details/49946429


Retrofit项目Github主页:点击打开链接

Retrofit项目官方文档   :点击打开链接


首先是我参考的文章:

● Retrofit 2.0:有史以来最大的改进

● 使用Retrofit请求API数据

● Retrofit2.0使用详解

● Retrofit 2.0使用详解,配合OkHttp、Gson,Android最强网络请求框架

● 用Retrofit 2 简化 HTTP 请求

这里感谢以上的作者对于 Retrofit使用的讲解,对我的帮助很大。

那么我根据自己的使用情况做一下汇总:因为也是第一次使用,没有接触过2.0之前的版本,所以不介绍与旧版区别。


1.设置


(1)权限:首先确保在AndroidManifest.xml中请求了网络权限 :


[java]  view plain  copy
 print ?
  1. <uses-permission android:name="android.permission.INTERNET" />  


(2)Studio用户,在app/build.gradle文件中添加如下代码:

[java]  view plain  copy
 print ?
  1. dependencies {  
  2.     compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'  
  3.     compile 'com.squareup.okhttp:okhttp:2.5.0'  
  4.     compile 'com.squareup.okio:okio:1.6.0'  
  5. }  

Eclipse的用户,可以下载最新的jar:我将整理的jar包已上传:点击打开链接
注意:1.Retrofit必须使用okhttp请求了,如果项目中没有okhttp的依赖的话,肯定会出错 。
           2.okhttp内部依赖okio所以也要添加。


2.使用


(1)创建Retrofit实例

[java]  view plain  copy
 print ?
  1. public static final String BASE_URL = "http://api.myservice.com";  
  2. Retrofit retrofit = new Retrofit.Builder()  
  3.     .baseUrl(BASE_URL)  
  4.     .build();  

如果你想接收json 结果并解析成DAO,你必须把Gson Converter 作为一个独立的依赖添加进来。

[java]  view plain  copy
 print ?
  1. compile 'com.google.code.gson:gson:2.4'  
  2. compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'  

这里是Square提供的官方Converter modules列表。选择一个最满足你需求的。


Gson: com.squareup.retrofit:converter-gson

Jackson: com.squareup.retrofit:converter-jackson

Moshi: com.squareup.retrofit:converter-moshi

Protobuf: com.squareup.retrofit:converter-protobuf

Wire: com.squareup.retrofit:converter-wire

Simple XML: com.squareup.retrofit:converter-simplexml


你也可以通过实现Converter.Factoty接口来创建一个自定义的converter。


然后使用addConverterFactory把它添加进来:

[java]  view plain  copy
 print ?
  1. public static final String BASE_URL = "http://api.myservice.com";  
  2. Retrofit retrofit = new Retrofit.Builder()  
  3.     .baseUrl(BASE_URL)  
  4.     .addConverterFactory(GsonConverterFactory.create())  
  5.     .build();  

(2)定义Endpoints,实现了转换HTTP API为Java接口


Retrofit提供了5种内置的注解:GET、POST、PUT、DELETE和HEAD,在注解中指定的资源的相对URL

[java]  view plain  copy
 print ?
  1. @GET("users/list")  

也可以在URL中指定查询参数

[java]  view plain  copy
 print ?
  1. @GET("users/list?sort=desc")  

请求的URL可以在函数中使用替换块和参数进行动态更新,替换块是{ and }包围的字母数字组成的字符串,相应的参数必须使用相同的字符串被@Path进行注释

[java]  view plain  copy
 print ?
  1. @GET("group/{id}/users")  
  2. Call<List<User>> groupList(@Path("id"int groupId);  

也可以添加查询参数

[java]  view plain  copy
 print ?
  1. @GET("group/{id}/users")  
  2. Call<List<User>> groupList(@Path("id"int groupId, @Query("sort") String sort);  

复杂的查询参数可以使用Map进行组合

[java]  view plain  copy
 print ?
  1. @GET("group/{id}/users")  
  2. Call<List<User>> groupList(@Path("id"int groupId, @QueryMap Map<String, String> options);  

可以通过@Body注解指定一个对象作为Http请求的请求体

[java]  view plain  copy
 print ?
  1. @POST("users/new")  
  2. Call<User> createUser(@Body User user);  

使用@FormUrlEncoded发送表单数据,使用@Field注解和参数来指定每个表单项的Key,Value为参数的值。

[java]  view plain  copy
 print ?
  1. @FormUrlEncoded  
  2. @POST("user/edit")  
  3. Call<User> getUser(@Field("name") String name, @Field("password") String password);  


使用@FormUrlEncoded发送表单数据时,表单项过多时可以使用Map进行组合

[java]  view plain  copy
 print ?
  1. @FormUrlEncoded  
  2. @POST("user/edit")  
  3. Call<User> getUser(@FieldMap Map<String, String> map);  

使用@Multipart可以进行文件上传,使用@Part指定文件路径及类型

[java]  view plain  copy
 print ?
  1. @Multipart  
  2. @POST("/user/edit")  
  3. Call<User> upload(@Part("image\"; filename=\"文件名.jpg") RequestBody file);  

使用@MapPart可以方便批量上传

[java]  view plain  copy
 print ?
  1. @Multipart  
  2. @POST("/user/edit")  
  3. Call<User> upload(@PartMap Map<String, RequestBody> params);  
[java]  view plain  copy
 print ?
  1. RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), imgFile);  
  2. map.put("image\"; filename=\""+imgFile.getName()+"", fileBody);  

(3)Accessing the API

[java]  view plain  copy
 print ?
  1. public interface MyApiEndpointInterface {  
  2.     // Request method and URL specified in the annotation  
  3.     // Callback for the parsed response is the last parameter  
  4.     @GET("/users/{username}")  
  5.     Call<User> getUser(@Path("username") String username);  
  6. }  
  7. MyApiEndpointInterface apiService = retrofit.create(MyApiEndpointInterface.class);  


异步请求这个API

[java]  view plain  copy
 print ?
  1. String username = "sarahjean";  
  2. Call<User> call = apiService.getUser(username);  
  3. call.enqueue(new Callback<User>() {  
  4.     @Override  
  5.     public void onResponse(Response<User> response) {  
  6.         int statusCode = response.code();  
  7.         User user = response.body();    
  8.     }  
  9.     @Override  
  10.     public void onFailure(Throwable t) {  
  11.         // Log error here since request failed  
  12.     }  
  13. });  

同步请求

[java]  view plain  copy
 print ?
  1. String username = "sarahjean";   
  2.   
  3.   
  4. Call<User> call = apiService.getUser(username);  
  5.   
  6.   
  7. User user = call.execute();  


3.注意


(1)我们在同步方法使用时可以直接调用execute方法,但是这个方法只能调用一次。解决办法:需要用clone方法生成一个新的之后在调用execute方法:

[java]  view plain  copy
 print ?
  1. Call<List<Contributor>> call = gitHubService.repoContributors("square""retrofit");  
  2. response = call.execute();  
  3. // This will throw IllegalStateException:  
  4. response = call.execute();  
  5. Call<List<Contributor>> call2 = call.clone();  
  6. // This will not throw:  
  7. response = call2.execute();  


(2)当我们执行的同步或异步加入队列后,可以随时使用cancel方法取消请求:

[java]  view plain  copy
 print ?
  1. Call<List<Contributor>> call = gitHubService.repoContributors("square""retrofit");  
  2.   
  3. call.enqueue(...);  
  4. // or...  
  5. call.execute();  
  6.   
  7. // later...  
  8. call.cancel();  
目录
相关文章
|
20天前
|
JSON Java 数据格式
rxjava2+retrofit2
rxjava2+retrofit2
27 1
|
9月前
|
缓存
Retrofit配置及各情况处理
Retrofit配置及各情况处理
163 0
|
JSON 安全 Java
Retrofit入门
Retrofit入门
|
设计模式 API
定制Retrofit
定制Retrofit
92 0
定制Retrofit
|
JSON Android开发 数据格式
RxJava+Retrofit示例 ,Retrofit 注解学习
RxJava+Retrofit示例 ,Retrofit 注解学习
122 0
|
API Android开发 Java
RxJava2 和 Retrofit2 结合使用详解
不讲 rxjava 和 retrofit 而是直接上手 2 了,因为 2 封装的更好用的更多。 1. 观察者模式 常见的 button 点击事件为例,button 是被观察者,listener 是观察者,setOnClickListener 过程是订阅,有了订阅关系后在 button 被点击的时候,监听者 listener 就可以响应事件。
|
缓存 API Android开发
浅谈OkHttp以及Retrofit+RxJava的封装使用
1.为什么我们要使用OkHttp?OkHttp有什么优点?  说OkHttp之前我们先说另外两个网络请求库——HttpUrlConnection和HttpClient。
2155 0
|
Android开发 Java
|
Java Android开发 流计算
|
JSON Java API
网络请求框架 Retrofit 2 使用入门
本文讲的是网络请求框架 Retrofit 2 使用入门,Retrofit 是一个用于 Android 和 Java 平台的类型安全的网络请求框架。Retrofit 通过将 API 抽象成 Java 接口而让我们连接到 REST web 服务变得很轻松。
1912 0