菜鸟笔记
提升您的技术认知

retrofit2.0中注解使用套路-ag真人游戏

之前有讲过retrofit2.0的简单使用和解析。最近在做retrofit替换之前使用的asynchttpclient,在替换的过程中遇到一些之前忽视的小细节。自己感觉知道这几点在开发中灵活使用retrofit非常有好处。

@query,@querymap,@field,@fieldmap,@formurlencoded,@path,@url
这七种注解应该是最常用的了。

下边列举各种应用场景。

一、get方式请求静态url地址

retrofit retrofit = new retrofit.builder()
    .base
    .build();
public interface githubservice {
  
    //无参数
    @get("users/stven0king/repos")
    call> listrepos();
    //少数参数
    @get("users/stven0king/repos")
    call> listrepos(@query("time") long time);
    //参数较多
    @get("users/stven0king/repos")
    call> listrepos(@querymap map params);
}

@query和@querymap也可以结合在一起使用。

要是对应的url在服务端支持get/post两种类型的请求的话,那么上面的@get变为@post也可以执行,只不过post请求时所带的参数也会像get方式一样已?key=value&key1=vaule2…的形式拼接在url的后边。

二、post方式请求静态url地址

retrofit retrofit = new retrofit.builder()
    .base
    .build()
public interface githubservice {
  
    //无参数
    @post("users/stven0king/repos")
    call> listrepos();
    //少数参数
    @formurlencoded
    @post("users/stven0king/repos")
    call> listrepos(@field("time") long time);
    //参数较多
    @formurlencoded
    @post("users/stven0king/repos")
    call> listrepos(@fieldmap map params);
}

@field和@fieldmap可以结合在一起使用。

另外是不是发现了比起@get多了一个@fromurlencoded的注解。如果去掉@fromurlencoded在post请求中使用@field和@fieldmap,那么程序会抛出java.lang.illegalargumentexception: @field parameters can only be used with form encoding. (parameter #1)的错误异常。如果将@fromurlencoded添加在@get上面呢,同样的也会抛出java.lang.illegalargumentexception:formurlencoded can only be specified on http methods with request body (e.g., @post).的错误异常。

三、半静态的url地址请求

retrofit retrofit = new retrofit.builder()
    .base
    .build()
public interface githubservice {
  
  @get("users/{user}/repos")
  call> listrepos(@path("user") string user);
}

四、动态的url地址请求

retrofit retrofit = new retrofit.builder()
    .base
    .build()
public interface githubservice {
  
  @get
  call> listrepos(@url string user);
}

五、总结小细节

  • 当@get或@post注解的url为全路径时(可能和baseurl不是一个域),会直接使用注解的url的域。
  • 如果请求为post实现,那么最好传递参数时使用@field、@fieldmap和@formurlencoded。因为@query和或querymap都是将参数拼接在url后面的,而@field或@fieldmap传递的参数时放在请求体的。
  • 使用@path时,path对应的路径不能包含”/”,否则会将其转化为/。在遇到想动态的拼接多节url时,还是使用@url吧。
网站地图