Retrofit对Okhttp3.0的封装

Retrofit 是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的,OkHttp现在已经得到Google官方认可,大量的app都采用OkHttp做网络请求。本文使用Retrofit2.0.0版本进行实例演示。

使用Retrofit可以进行GET,POST,PUT,DELETE等请求方式。

同步请求:需要在子线程中完成,会阻塞主线程。

Response response = call.execute().body();

异步请求:请求结果在主线程中回调,可以在onResponse()回调方法进行更新UI。

call.enqueue(Callback callback)

使用步骤:

(1) 创建工程,添加jar:

?
1
2
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    compile 'com.squareup.retrofit2:converter-gson:2.4.0'

(2) 创建业务请求接口,具体代码如下
请求之前首先权限配置都要配置了
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
  * 创建业务请求接口
  */
 
public interface IUserService {
  /**
   * GET请求
   */
  @GET ( "Servlet/UserServlet" )
  Call<User> getUser( @Query ( "email" ) String email);
 
  /**
   * POST请求
   */
  @FormUrlEncoded
  @POST ( "UserServlet" )
  Call<User> postUser( @Field ( "name" ) String name, @Field ( "email" ) String email);
}

解释说明:

@GET注解表示GET请求,@Query表示请求参数,将会以key=value(@Query注解参数名称为key,调用传进来的值为value)的方式拼接在url后面.

@POST注解表示POST请求,@FormUrlEncoded将会自动将请求参数的类型设置为application/x-www-form-urlencoded,@FormUrlEncoded注解不能用于Get请求。@Field注解将每一个请求参数都存放至请求体中,还可以添加encoded参数,该参数为boolean型,具体的用法为:
@Field(value = "password", encoded = true) String pwd
encoded参数为true的话,key-value-pair将会被编码,即将中文和特殊字符进行编码转换.

(3)创建Retrofit对象

?
1
2
3
4
5
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Constant.BASE_URL)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
IUserService iUserService = retrofit.create(IUserService. class );

解释说明:

baseUrl()方法制定网络请求的固定绝对地址,一般包括请求协议(如Http)、域名或IP地址、端口号。
创建Retrofit实例时,若没有配置addConverterFactory(GsonConverterFactory.create())将会回调出JSON字符串,配置了将会回调实体对象。

支持的JSON解析库:

Gson: compile ‘com.squareup.retrofit2:converter-gson:2.0.1'
Jackson: compile ‘com.squareup.retrofit2:converter-jackson:2.0.1'
Moshi: compile ‘com.squareup.retrofit2:converter-moshi:2.0.1'
Protobuf: compile ‘com.squareup.retrofit2:converter-protobuf:2.0.1'
Wire: compile ‘com.squareup.retrofit2:converter-wire:2.0.1'
Simple XML: compile ‘com.squareup.retrofit2:converter-simplexml:2.0.1'
Scalars (primitives, boxed, and String): compile ‘com.squareup.retrofit2:converter-scalars:2.0.1'

(4) 调用请求方法,并得到Call实例

?
1
Call<ResponseBody> call = iUserService.getUser(xing-java @foxmail .com);

(5) 使用Call实例完成同步或异步请求

?






7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
   * 发送GET请求
   */
  private void getRequest() {
   Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Constant.BASE_URL)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
   IUserService iUserService = retrofit.create(IUserService. class );
   Call<User> call = iUserService.getUser( "[email protected]" );
   call.enqueue( new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
 
     Log.i( "MainActivity" , "response = " + response);
     User user = response.body();
     resTxtView.setText(user.toString());
    }
 
    @Override
    public void onFailure(Call<User> call, Throwable t) {
 
    }
   });
  }

请求方式:

(1)GET 请求:

GET 请求返回 JSON 字符串:

这里写图片描述

GET 请求返回实体对象:

这里写图片描述

(2) POST发送表单:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
  * 发送POST请求
  */
private void postRequest() {
  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Constant.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  IUserService iUserService = retrofit.create(IUserService. class );
  Call<User> call = iUserService.postUser( "star.tao" , "[email protected]" );
  call.enqueue( new Callback<User>() {
   @Override
   public void onResponse(Call<User> call, Response<User> response) {
   }
 
   @Override
   public void onFailure(Call<User> call, Throwable throwable) {
 
   }
  });

服务端接收到的结果:

这里写图片描述

(3)文件上传:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void uploadFile() {
   Retrofit retrofit = new Retrofit.Builder()
     .addConverterFactory(GsonConverterFactory.create())
     .baseUrl(Constant.BASE_URL)
     .build();
   IUserService iUserService = retrofit.create(IUserService. class );
   File file = new File( "/sdcard/s.png" );
   RequestBody fileRequestBody = RequestBody.create(MediaType.parse( "multipart/form-data" ), file);
   MultipartBody.Part multipartBody = MultipartBody.Part.createFormData( "upload_file" , file.getName(), fileRequestBody);
   String desc = "this is file description" ;
   RequestBody descRequestBody = RequestBody.create(MediaType.parse( "multipart/form-data" ), desc);
   Call<ResponseBody> call = iUserService.uploadFile(descRequestBody, multipartBody);
   call.enqueue( new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
     Log.i( "debug" , "upload success" );
    }
 
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
 
    }
   });
 
  }

猜你喜欢

转载自blog.csdn.net/l6666_6666/article/details/79933856