Retrofit2.0使用详解

Retrofit2.0使用


初次了解Retrofit

Retrofit项目Github主页
Retrofit项目官方文档
在介绍Retrofit前要先对其有明确的认识.Retrofit 和Java领域的ORM概念类似, ORM把结构化数据转换为Java对象,而Retrofit 把REST API返回的数据转化为Java对象方便操作。同时还封装了网络代码的调用。
比如:

public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

定义上面的一个REST API接口。 该接口定义了一个函数 listRepos , 该函数会通过HTTP GET请求去访问服务器的/users/{user}/repos路径并把返回的结果封装为List Java对象返回。

其中URL路径中的{user}的值为listRepos 函数中的参数 user的取值。

然后通过 RestAdapter 类来生成一个 GitHubService 接口的实现;

GitHubService service = restAdapter.create(GitHubService.class);

获取接口的实现后就可以调用接口函数来和服务器交互了;

List<Repo> repos = service.listRepos("octocat");

从上面的示例可以看出, Retrofit 使用注解来声明HTTP请求
* 支持 URL 参数替换和查询参数
* 返回结果转换为Java对象(返回结果可以为 JSON, protocol buffers)
* 支持 Multipart请求和文件上传


具体的使用文档

函数和函数参数上的注解声明了请求方式
* 请求方式
每个函数都必须带有 HTTP 注解来表明请求方式和请求的URL路径。类库中有5个HTTP注解: GET , POST , PUT , DELETE , 和 HEAD。 注解中的参数为请求的相对URL路径。

@GET("/users/list")

在URL路径中也可以指定URL参数

@GET("/users/list?sort=desc")
  • URL处理
    请求的URL可以根据函数参数动态更新。一个可替换的区块为用 { 和 } 包围的字符串,而函数参数必需用 @Path 注解表明,并且注解的参数为同样的字符串
@GET("/group/{id}/users") //注意 字符串id
List<User> groupList(@Path("id") int groupId); //注意 Path注解的参数要和前面的字符串一样 id
  • 还支持查询参数
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);

请求体(Request Body)

通过 @Body 注解可以声明一个对象作为请求体发送到服务器。

@POST("/users/new")
void createUser(@Body User user, Callback<User> cb);

对象将被 RestAdapter 使用对应的转换器转换为字符串或者字节流提交到服务器。

FORM ENCODED AND MULTIPART 表单和Multipart

函数也可以注解为发送表单数据和multipart 数据

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

@FormUrlEncoded
@POST("/user/edit")
User updateUser(@Field("first_name") String first, @Field("last_name") String last);

使用 @Multipart 注解来发送multipart数据。使用 @Part 注解定义要发送的每个文件。

@Multipart
@PUT("/user/photo")
User updateUser(@Part("photo") TypedFile photo, @Part("description") TypedString description);

Multipart 中的Part使用 RestAdapter 的转换器来转换,也可以实现 TypedOutput 来自己处理序列化。

异步 VS 同步

每个函数可以定义为异步或者同步。

具有返回值的函数为同步执行的。

@GET("/user/{id}/photo")
Photo listUsers(@Path("id") int id);

而异步执行函数没有返回值并且要求函数最后一个参数为Callback对象

@GET("/user/{id}/photo")
void listUsers(@Path("id") int id, Callback<Photo> cb);

在 Android 上,callback对象会在主(UI)线程中调用。而在普通Java应用中,callback在请求执行的线程中调用。

服务器结果转换为Java对象

使用RestAdapter的转换器把HTTP请求结果(默认为JSON)转换为Java对象,Java对象通过函数返回值或者Callback接口定义

@GET("/users/list")
List<User> userList();

@GET("/users/list")
void userList(Callback<List<User>> cb);

如果要直接获取HTTP返回的对象,使用 Response 对象。

@GET("/users/list")
Response userList();

@GET("/users/list")
void userList(Callback<Response> cb);

Retrofit2.0的新知识点

首先为大家提供一些文章关于Retrofit2.0的改进和使用的方法文章.
* Retrofit 2.0:有史以来最大的改进
* 使用Retrofit请求API数据
* Retrofit2.0使用详解
* Retrofit 2.0使用详解,配合OkHttp、Gson,Android最强网络请求框架
* 用Retrofit 2 简化 HTTP 请求
以上文章都是对Retrofit的使用讲解.

Retrofit2.0的使用方式

请按照一下步骤进行配置:
* 权限:首先确保在AndroidManifest.xml中请求了网络权限 :

  <uses-permission android:name="android.permission.INTERNET" />
  • Studio用户,在app/build.gradle文件中添加如下代码:
dependencies {
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    compile 'com.squareup.okio:okio:1.6.0'
}

注意
1.Retrofit必须使用okhttp请求了,如果项目中没有okhttp的依赖的话,肯定会出错 。
2.okhttp内部依赖okio所以也要添加


使用

  • 创建Retrofit实例
public static final String BASE_URL = "http://api.myservice.com";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .build();
如果你想接收json 结果并解析成DAO,你必须把Gson Converter 作为一个独立的依赖添加进来。
compile 'com.google.code.gson:gson:2.4'
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把它添加进来:

public static final String BASE_URL = "http://api.myservice.com";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  • 定义Endpoints,实现了转换HTTP API为Java接口

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

@GET("users/list")

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

@GET("users/list?sort=desc")

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

@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);

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

@POST("users/new")
Call<User> createUser(@Body User user);

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

@FormUrlEncoded
@POST("user/edit")
Call<User> getUser(@Field("name") String name, @Field("password") String password);

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

@FormUrlEncoded
@POST("user/edit")
Call<User> getUser(@FieldMap Map<String, String> map);

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

@Multipart
@POST("/user/edit")
Call<User> upload(@Part("image\"; filename=\"文件名.jpg") RequestBody file);

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

@Multipart
@POST("/user/edit")
Call<User> upload(@PartMap Map<String, RequestBody> params);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), imgFile);
map.put("image\"; filename=\""+imgFile.getName()+"", fileBody);
  • Accessing the API
public interface MyApiEndpointInterface {
    // Request method and URL specified in the annotation
    // Callback for the parsed response is the last parameter
    @GET("/users/{username}")
    Call<User> getUser(@Path("username") String username);
}
MyApiEndpointInterface apiService = retrofit.create(MyApiEndpointInterface.class);

异步请求这个API

String username = "sarahjean";
Call<User> call = apiService.getUser(username);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Response<User> response) {
        int statusCode = response.code();
        User user = response.body();  
    }
    @Override
    public void onFailure(Throwable t) {
        // Log error here since request failed
    }
});

同步请求

String username = "sarahjean"; 


Call<User> call = apiService.getUser(username);


User user = call.execute();

注意

  • 我们在同步方法使用时可以直接调用execute方法,但是这个方法只能调用一次。解决办法:需要用clone方法生成一个新的之后在调用execute方法:
Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
response = call.execute();
// This will throw IllegalStateException:
response = call.execute();
Call<List<Contributor>> call2 = call.clone();
// This will not throw:
response = call2.execute();
  • 当我们执行的同步或异步加入队列后,可以随时使用cancel方法取消请求:
Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");

call.enqueue(...);
// or...
call.execute();

// later...
call.cancel();

### 调用代码
* 接口声明

   public interface GetBaidu{
      @GET("http://www.baidu.com/")
      Call<ResponseBody> get();
    //Call<T> get();//必须是这种形式,这是2.0之后的新形式
//我这里需要返回网页内容,不需要转换成Json数据,所以用了ResponseBody;
//你也可以使用Call<GsonBean> get();这样的话,需要添加Gson转换器...后续介绍
  }
  • 调用接口
//经过测试: baseUrl必须设置,如果 声明接口时@GET使用了完整的url路径,那么baseUrl就会被忽略,否则就是拼接url
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com/").build();//在这里可以添加 Gson转换器等;
  GetBaidu getBaidu = retrofit.create(GetBaidu.class);//使用上面声明的接口创建
  Call<ResponseBody> call = getBaidu.get();//获取一个Call,才可以执行请求

//同步请求....
  try {
      Response<ResponseBody> bodyResponse = call.execute();
      String body = bodyResponse.body().string();//获取返回体的字符串
      Log.e(TAG, "");
  } catch (IOException e) {
      e.printStackTrace();
  }

//异步请求....
  call.enqueue(new Callback<ResponseBody>() {//异步
      @Override
      public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
          try {
              String body = response.body().string();//获取返回体的字符串
          } catch (IOException e) {
              e.printStackTrace();
          }
          Log.e(TAG, "");
      }

      @Override
      public void onFailure(Throwable t) {
          Log.e(TAG, "");
      }
  });

如果有帮助别忘打赏哦:

微信打赏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值