美文网首页
android study: Retrofit

android study: Retrofit

作者: HenryBlue | 来源:发表于2017-05-26 12:20 被阅读0次

Retrofit 简介

Retrofit 是一套由Square所开发维护,將RESTfulAPI 写法规范和模块化的函数库。底层也使用他们的Okhttp,Retrofit 2默认使用OKHttp作为网络层,并且在它上面进行构建。

官方描述:用于Android和Java的一个类型安全(type-safe)的REST客户端

你将会用注解去描述HTTP请求,同时Retrofit默认集成URL参数替换和查询参数.除此之外它还支持 Multipart请求和文件上传。

添加依赖

compile'com.squareup.retrofit2:converter-gson:2.2.0'

compile'com.squareup.okhttp3:logging-interceptor:3.8.0'

定义接口

在这一步,需要将我们的 API 接口地址转化成一个 Java 接口。
我们的 API 接口地址为:

https://api.github.com/users/Guolei1130

转化写成 Java 接口为

public interface APIInterface{
    @GET("/users/{user}")  
    Call<TestModel> repo(@Path("user") String user);
}

在此处 GET 的意思是 发送一个 GET请求,请求的地址为:baseUrl + "/users/{user}"。

{user} 类似于占位符的作用,具体类型由 repo(@Path("user") String user) 指定,这里表示 {user} 将是一段字符串。

Call<TestModel> 是一个请求对象,<TestModel>表示返回结果是一个 TestModel 类型的实例。

定义 Model

请求会将 Json 数据转化为 Java 实体类,所以我们需要自定义一个 Model:

public class TestModel {
  private String login;

  public String getLogin() {
    return login;
  }

  public void setLogin(String login) {
    this.login = login;
  }
}

进行连接通信

现在我们有了『要连接的 Http 接口』和 『要返回的数据结构』,就可以开始执行请求啦。

首先,构造一个 Retrofit 对象:

Retrofit retrofit= new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();

注意这里添加的 baseUrl 和 GsonConverter,前者表示要访问的网站,后者是添加了一个转换器。

接着,创建我们的 API 接口对象,这里 APIInterface 是我们创建的接口:
APIInterface service = retrofit.create(APIInterface.class);

使用 APIInterface 创建一个『请求对象』:
Call<TestModel> model = service.repo("Guolei1130");

注意这里的 .repo("Guolei1130") 取代了前面的 {user}。到这里,我们要访问的地址就成了:

https://api.github.com/users/Guolei1130

可以看出这样的方式有利于我们使用不同参数访问同一个 Web API 接口,比如你可以随便改成 .repo("ligoudan")
最后,就可以发送请求了!

model.enqueue(new Callback<TestModel>() { 
  @Override 
  public void onResponse(Call<TestModel> call,       
                       Response<TestModel>response) { 
    // Log.e("Test", response.body().getLogin());   
     System.out.print(response.body().getLogin());
 } 

  @Override 
  public void onFailure(Call<TestModel> call, Throwable t) {   
       System.out.print(t.getMessage()); } 
});

至此,我们就利用 Retrofit 完成了一次网络请求。

GET 请求参数设置

在我们发送 GET 请求时,如果需要设置 GET 时的参数,Retrofit 注解提供两种方式来进行配置。分别是 @Query(一个键值对)和 @QueryMap(多对键值对)。

Call<TestModel> one(@Query("username") String username);
Call<TestModel> many(@QueryMap Map<String, String> params);

POST 请求参数设置

POST 的请求与 GET 请求不同,POST 请求的参数是放在请求体内的。

所以当我们要为 POST 请求配置一个参数时,需要用到 @Body 注解:

Call<TestModel> post(@Body User user);
这里的 User 类型是需要我们去自定义的:

public class User {
  public String username;
  public String password;

  public User(String username,String password){
    this.username = username;
    this.password = password;
}

最后在获取请求对象时:
User user = new User("lgd","123456");
Call<TestModel> model = service.post(user);

就能完成 POST 请求参数的发送,注意该请求参数 user 也会转化成 Json 格式的对象发送到服务器。

以上内容摘自: http://www.jianshu.com/p/b64a2de066c3 (对作者表示感谢)

我的总结

// 在链接时会替换掉URL中{}中的内容,例如:[http://your.api-base.url/group/123/users](http://your.api-base.url/group/123/users)
@GET("/group/{id}/users")      //注意 字符串id
List<User> groupList(@Path("id") int groupId);  //注意 Path注解的参数要和前面的字符串一样 id

// 例如:(http://your.api-base.url/group/123/users)
@GET("/group/{id}/{name}") 
List<User> groupList(@Path("id") int groupId, @Path("name")  String name); 

// 还支持查询参数,@Query相当于在URL后加上问号和后面的参数,例如:(http://your.api-base.url/group/123/users?sort=1)
@GET("/group/{id}/users")
List<User> groupList(@Path("id")  int groupId, @Query("sort") String sort);
 
// 多个Query之间通过&连接,例如 (http://your.api-base.url/group/123/users?newsId=123&sort=1)
@GET("/group/{id}/users")
List<User> groupList(@Path("id")  int groupId, @Query("newsId") String newsId, @Query("sort") String sort);

// 假如需要添加相同Key值,但是value却有多个的情况,一种方式是添加多个@Query参数,还有一种简便的方式是将所有的value放置在列表中,然后在同一个@Query下完成添加
// 例如:[http://your.api-base.url/group/123/users?newsId=123&newsId=345]
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query
("newsId") List<String> newsId);

 // 也可以多个参数在URL问号之后,且个数不确定,例如(http://your.api-base.url/group/123/users?newsId=123&sort=1)
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap
 Map<String, String> map);

// 也可以为固定参数与动态参数的混用
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query
("newsId") String newsId, @QueryMap Map<String, String> map);

  // Query非必填,也就是说即使不传该参数,服务端也可以正常解析,但请求方法定义处还是需要完整的Query注解,某次请求如果不需要传该参数的话,只需填充null即可
List<User> repos = service.groupList(123, null);

// 若需要重新定义接口地址,可以使用@Url,将地址以参数的形式传入即可
@GET
Call<List<Activity>> getActivityList(@Url String url, @QueryMap Map<String, String> map);

对请求进行统一封装

public abstract class BaseRequest<M> {

    protected abstract Call<M> getCall();

    private int tag;

    private WeakReference<IRequestCallback> callbackWeakReference;

    public void exe(final IRequestCallback requestCallback, final int tag) {

        final IRequestCallback callback = checkCallback();

        if (callback == null) return;
        callback.onRequestStart(tag);

        getCall().enqueue(new Callback<M>() {

            @Override
            public void onResponse(Call<M> call, Response<M> response) {

                if (response.isSuccessful()) {
                    if (callback == null) return;
                    callback.onRequestSucc(tag, response.body());
                } else {
                    String error = response.message();
                    int code = response.code();
                    String message = code + ":" + error;
                    ServerException exception = new ServerException(message);
                    callback.onRequestException(tag, exception);
                    LogUtil.log("base response 错误:" + message);
                }

            }

            @Override
            public void onFailure(Call<M> call, Throwable e) {
                Throwable exception = e.getCause();
                IRequestCallback callback = checkCallback();
                if (callback == null) return;

                callback.onRequestException(tag, (Exception) exception);
            }
        });

        if (callback == null) return;
        callback.onRequestFinal(tag);
    }

    public void cancel() {
        getCall().cancel();
    }

编写service

public interface TestService {

    @GET("jxc/merchant_info/query_merchant_info")
    Call<UserInfoGson> getUserInfoJSON(@Query("merchantNo") String merchantNo);

    /**
     *
     * 如果不需要转换成Json数据,可以用了ResponseBody;
     * @param merchantNo
     * @return
     */
    @GET("jxc/merchant_info/query_merchant_info")
    Call<ResponseBody> getUserInfoString(@Query("merchantNo") String merchantNo);

    @GET("jxc/merchant_info/query_merchant_info")
    Call<UserInfoGson> getUserInfoJSON(@QueryMap HashMap<String ,String> map);

    /**
     *
     * POST JSON 请求, 结果不转成GSON 使用String
     *
     * @param route
     * @return
     */
    @Headers({"Content-type:application/json;charset=UTF-8"})
    @POST("/jxc/customer/add")
    Call<ResponseBody> addMember(@Body RequestBody route);

    @FormUrlEncoded
    @POST("/jxc/customer/add")
    Call<ResponseBody> addMember2(@Field("loginName") String username,
                                  @Field("password") String password);
}

编写request

public class UserInfoRequest extends BaseRequest<TestService> {

    private HashMap<String , String> param;

    public UserInfoRequest(HashMap<String, String> param) {
        this.param = param;
    }

    //.getUserInfoJSON("66283")
    @Override
    protected Call<UserInfoGson> getCall() {
          return   NetFactory.getRetrofit().
                              create(getServiceClass()).
                                     getUserInfoJSON(param);
    }

    @Override
    protected Class<TestService> getServiceClass() {
        return TestService.class;
    }
}

发起请求
new UserInfoRequest(param).exe(callback, tag)

public class CustomConverterFactory extends Converter.Factory{

private Gson gson;

public CustomConverterFactory(Gson gson) {
    this.gson = gson;
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    //return super.responseBodyConverter(type, annotations, retrofit);

    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    return new CustomResponseConverter<>(gson, adapter);
}

@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}

}

/**

public class CustomResponseConverter <T> implements Converter<ResponseBody, T> {

private final Gson gson;
private final TypeAdapter<T> adapter;

public CustomResponseConverter(Gson gson, TypeAdapter<T> adapter) {
    this.gson = gson;
    this.adapter = adapter;
}

@Override
public T convert(ResponseBody value) throws IOException {
    try {
        String body = value.string();

        LogUtil.log("converter response: " + body);

        return adapter.fromJson(body)

    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    } finally {
        value.close();
    }
}

}

相关文章

网友评论

      本文标题:android study: Retrofit

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