当前位置: 移动技术网 > IT编程>移动开发>Android > Android中Retrofit+OkHttp进行HTTP网络编程的使用指南

Android中Retrofit+OkHttp进行HTTP网络编程的使用指南

2019年07月24日  | 移动技术网IT编程  | 我要评论

sssccclll,伤城之恋下载,炼宝专家txt

retrofit介绍:
retrofit(github主页https://github.com/square/okhttp)和okhttp师出同门,也是square的开源库,它是一个类型安全的网络请求库,retrofit简化了网络请求流程,基于okhtttp做了封装,解耦的更彻底:比方说通过注解来配置请求参数,通过工厂来生成calladapter,converter,你可以使用不同的请求适配器(calladapter), 比方说rxjava,java8, guava。你可以使用不同的反序列化工具(converter),比方说json, protobuff, xml, moshi等等。
官网 http://square.github.io/retrofit/
github https://github.com/square/retrofit

retrofit使用:
1.在build.gradle中添加如下配置

compile 'com.squareup.retrofit2:retrofit:2.0.2'

2.初始化retrofit

   retrofit = new retrofit.builder()
        .baseurl(base_url)
        .addconverterfactory(fastjsonconverterfactory.create())
        .client(mokhttpclient)
        .build();

3.初始化okhttpclient

    okhttpclient.builder builder = new okhttpclient().newbuilder()
        .connecttimeout(10, timeunit.seconds)//设置超时时间
        .readtimeout(10, timeunit.seconds)//设置读取超时时间
        .writetimeout(10, timeunit.seconds);//设置写入超时时间
    int cachesize = 10 * 1024 * 1024; // 10 mib
    cache cache = new cache(app.getcontext().getcachedir(), cachesize);
    builder.cache(cache);
    builder.addinterceptor(interceptor);
    mokhttpclient = builder.build();
关于okhttp的拦截器、cache-control等这里就不再做解说了

4.关于converterfactory
对于okhttpclient的初始化我们都已经很熟悉了,对converterfactory初次接触多少有点陌生,其实这个就是用来统一解析responsebody返回数据的。

常见的converterfactory

gson: com.squareup.retrofit2:converter-gson
jackson: com.squareup.retrofit2:converter-jackson
moshi: com.squareup.retrofit2:converter-moshi
protobuf: com.squareup.retrofit2:converter-protobuf
wire: com.squareup.retrofit2:converter-wire
simple xml: com.squareup.retrofit2:converter-simplexml
scalars (primitives, boxed, and string): com.squareup.retrofit2:converter-scalars

由于项目中使用的是fastjson,所以只能自己自定义converterfactory。 

5.定义接口 get 请求
(1)get请求 不带任何参数

public interface iapi {

  @get("users")//不带参数get请求
  call<list<user>> getusers();

}

(2)get请求 动态路径 @path使用

public interface iapi {

  @get("users/{groupid}")//动态路径get请求
  call<list<user>> getusers(@path("userid") string userid);

}


(3)get请求 拼接参数 @query使用
public interface iapi {

  @get("users/{groupid}")
  call<list<user>> getusers(@path("userid") string userid, @query("age")int age);

}

6.定义接口 post请求
(1)post请求 @body使用

public interface iapi {

  @post("add")//直接把对象通过converterfactory转化成对应的参数
  call<list<user>> adduser(@body user user);

}

(2)post请求 @formurlencoded,@field使用   

public interface iapi {

 @post("login")
  @formurlencoded//读参数进行urlencoded
  call<user> login(@field("userid") string username, @field("password") string password);

}

(3)post请求 @formurlencoded,@fieldmap使用  

public interface iapi {

  @post("login")
  @formurlencoded//读参数进行urlencoded
  call<user> login(@fieldmap hashmap<string, string> paramsmap);

}

(4)post请求 @multipart,@part使用

public interface iapi {

  @multipart
  @post("login")
  call<user> login(@part("userid") string userid, @part("password") string password);

}

7.cache-control缓存控制  

public interface iapi {

  @headers("cache-control: max-age=640000")
  @get("users")//不带参数get请求
  call<list<user>> getusers();

}


8.请求使用
(1)返回iapi
  /**
   * 初始化api
   */
  private void initiapi() {
    iapi = retrofit.create(iapi.class);
  }
  /**
   * 返回api
   */
  public static iapi api() {

    return api.iapi;
  }


(2)发送请求

  call<string> call = api.api().login(userid,password);
  call.enqueue(new callback<string>() {
  @override
  public void onresponse(call<string> call, response<string> response) {
    log.e("", "response---->" + response.body());
  }

  @override
  public void onfailure(call<string> call, throwable t) {
    log.e("", "response----失败");
  }
  });

9.拦截器配置

拦截器配置要点
引入依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
先说 okhttp 3.0 的配置,3.0 使用层面上的主要改变是,由原本的 okhttp 对象直接各种 set 进行配置改为 builder 配置模式,所以原本对应的方法应该到 okhttpclient.builder 类对象下寻找。我的一些常用配置如下:
httplogginginterceptor interceptor = new httplogginginterceptor();
interceptor.setlevel(httplogginginterceptor.level.body);
okhttpclient client = new okhttpclient.builder()
    .addinterceptor(interceptor)
    .retryonconnectionfailure(true)
    .connecttimeout(15, timeunit.seconds)
    .addnetworkinterceptor(mtokeninterceptor)
    .build();
解释:
(1)httplogginginterceptor 是一个拦截器,用于输出网络请求和结果的 log,可以配置 level 为 basic / headers / body,都很好理解,对应的是原来 retrofit 的 set log level 方法,现在 retrofit 已经没有这个方法了,所以只能到 okhttp 这边来配置,并且 body 对应原来到 full.
(2)retryonconnectionfailure 方法为设置出现错误进行重新连接。
(3)connecttimeout 设置超时时间
(4)addnetworkinterceptor 让所有网络请求都附上你的拦截器,我这里设置了一个 token 拦截器,就是在所有网络请求的 header 加上 token 参数,下面会稍微讲一下这个内容。
让所有网络请求都附上你的拦截器:
interceptor mtokeninterceptor = new interceptor() {
  @override public response intercept(chain chain) throws ioexception {
    request originalrequest = chain.request();
    if (your.stoken == null || alreadyhasauthorizationheader(originalrequest)) {
      return chain.proceed(originalrequest);
    }
    request authorised = originalrequest.newbuilder()
      .header("authorization", your.stoken)
      .build();
    return chain.proceed(authorised);
  }
};
解释:
(1)那个 if 判断意思是,如果你的 token 是空的,就是还没有请求到 token,比如对于登陆请求,是没有 token 的,只有等到登陆之后才有 token,这时候就不进行附着上 token。另外,如果你的请求中已经带有验证 header 了,比如你手动设置了一个另外的 token,那么也不需要再附着这一个 token.
(2)header 的 key 通常是 authorization,如果你的不是这个,可以修改。
(3)如果你需要在遇到诸如 401 not authorised 的时候进行刷新 token,可以使用 authenticator,这是一个专门设计用于当验证出现错误的时候,进行询问获取处理的拦截器:
authenticator mauthenticator = new authenticator() {
  @override public request authenticate(route route, response response)
      throws ioexception {
    your.stoken = service.refreshtoken();
    return response.request().newbuilder()
            .addheader("authorization", newaccesstoken)
            .build();    
  }
}
然后,对于以上的两个拦截器,分别使用 okhttpclient.builder 对象的 addnetworkinterceptor(mtokeninterceptor) 和 authenticator(mauthenticator) 即可。
retrofit:
对于 retrofit,我的配置是:
retrofit retrofit = new retrofit.builder()
    .baseurl(appconfig.base_url)
    .client(client)
    .addcalladapterfactory(rxjavacalladapterfactory.create())
    .addconverterfactory(gsonconverterfactory.create(gson))
    .build();
service = retrofit.create(yourapi.class);
解释:
(1)baseurl: 原来的 setendpoint 方法变成了 baseurl
(2)client 即上面的 okhttp3 对象
(3)addcalladapterfactory 增加 rxjava 适配器
(4)addconverterfactory 增加 gson 转换器

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网