美文网首页Android 学习
retrofit2 基本使用

retrofit2 基本使用

作者: 锐_nmpoi | 来源:发表于2017-11-12 08:38 被阅读31次
//Retrofit2所需要的包
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//ConverterFactory的Gson依赖包  
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
//ConverterFactory的String依赖包
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
//ConverterFactory的String依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'

这里需要值得注意的是导入的retrofit2包的版本必须要一致,否则就会报错。

Get

第一步:将Rest API转换为java接口

public interface ApiManager {

@GET("Login")
Call<LoginResult> getData(@Query("account") String name, @Query("psw") String pw);

}

拼接结果为:http://192.168.56.1:8080/RetrofitTest/Login?account=?&psw=?

在此要同时建立好模型

public class LoginResult {

String msg;
public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}
}

第二步Retrofit会帮我们自动生成接口的实现类的实例,代码如下:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.56.1:8080/RetrofitTest/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
  1. baseUrl务必是/结尾

  2. //增加返回值为Gson的支持(以实体类返回)

    addConverterFactory(GsonConverterFactory.create())

  1. //这里采用的是Java的动态代理模式

    ApiManager apiManager = retrofit.create(ApiManager.class);

  2. //传入我们请求的键值对的值

    Call<LoginResult> data = apiManager.getData("123123", "123123");.

  3.  data.enqueue(new Callback<LoginResult>() {
         @Override
         public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
             if(response.isSuccessful()){
                //返回值为200
             }else{
                //返回值不是200
             }
    
         }
    
         @Override
         public void onFailure(Call<LoginResult> call, Throwable t) {
             //访问失败
         }
     });
    

//返回成功时,会自动解析Json , 封装成模型
所以直接调用为:

LoginResult body = response.body();
body.getMsg();

一些注解介绍

@GET //get请求

@Get("") //get请求带上Url

@Query //参数 键值对

@Url //参数
例如:
@GET
Call<LoginResult> getData2(@Url String url,@Query("account") String name, @Query("psw") String pw);

有时我们需要对于一个id参数传入多个值,比如这样:

https://api.example.com/tasks?id=123&id=124&id=125

对于这样的需求,Retrofit 通过传入一个List来实现:

public interface TaskService {  
@GET("/tasks")
Call<List<Task>> getTask(@Query("id") List<Long> taskIds);
}

这样,拼接后的URL就是我们需要的那样。

我们可以传入null,Retrofit 会忽略值为null的参数。

service.getTasks(null);

需要注意的是,可忽略参数的参数类型不能是int, float, long这些基本类型,应该用Integer, Float, Long来代替。

Post

  1. @POST("Login")

    Call<LoginResult> postData( @Query("account") String name, @Query("psw") String pw);

    与Get 是一样的

相关文章

网友评论

    本文标题:retrofit2 基本使用

    本文链接:https://www.haomeiwen.com/subject/tdlnmxtx.html