Retrofit 2.1 笔(基础)

Android 网路请求框架

一、自定义RetrofitManage类

0.添加Retrofit2的依赖
compile 'com.squareup.retrofit2:retrofit:2.1.0'
1.Retrofit的获取
Retrofit retrofit = new Retrofit.Builder()
    // 服务器请求URL
    .baseUrl("http://192.168.1.100/apiServer/")
    // 添加Gson转换器 需添加依赖 'com.squareup.retrofit2:converter-gson:2.1.0'
    .addConverterFactory(GsonConverterFactory.create())
    // OkHttp3 对象
    .client(client)
    .build();

Retrofit2 已支持的转换器(除此之外可以自定义Converter)

类型 依赖

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

2.OkHttpClient的获取
// OkHttp3 配置
OkHttpClient client = new OkHttpClient.Builder()
    // 添加拦截器
    .addInterceptor(authInterceptor)
    // 连接超时时间
    .connectTimeout(7676, TimeUnit.SECONDS)
    // 读取时间
    .readTimeout(7676, TimeUnit.SECONDS)
    .build();

// addInterceptor : 设置应用拦截器,可用于设置公共参数,头信息,日志拦截等
// connectTimeout : 设置超时时间
// readTimeout : 设置读取时间
3.Interceptor(拦截器)的创建

实现步骤:

  • 继承Interceptor类

  • 重写intercept方法

  • 继续执行拦截的请求则 return chain.proceed();

    package com.demon.retrofit20.http;

    import java.io.IOException;

    import okhttp3.Interceptor;
    import okhttp3.Request;
    import okhttp3.Response;

    /**

    • @author Demon

    • @version V1.0

    • @Description: OkHttpClient 授权拦截器

    • @date 2016年10月13日11:22:43
      */
      public class OAuthInterceptor implements Interceptor {

      static String PHONE;
      static String TOKEN;

      public OAuthInterceptor(String phone, String token) {
      PHONE = phone;
      TOKEN = token;
      }

      /**

      • 1.仅添加请求头
        */
        @Override
        public Response intercept(Chain chain) throws IOException {
        if (PHONE == null || TOKEN == null) {
        Request request = chain.request();
        return chain.proceed(request);
        } else {
        // 凭证
        String credentials = PHONE + "&" + TOKEN;
        Request authorised = chain.request().newBuilder()
        // 请求头添加验证
        .header("Authorization", credentials)
        .build();
        // 继续进行这个请求
        return chain.proceed(authorised);
        }
        }

      /**

      • 2.添加请求头+请求体 / 请求体
        @Override
        public Response intercept(Chain chain) throws IOException {
        // 获取构建的请求
        Request.Builder builder = chain.request().newBuilder();
        // 添加请求头内容
        builder.addHeader("Authorization", "demon");

        // 创建一个新的请求体
        RequestBody formBody = new FormBody.Builder()
        .add("validateCode", "[email protected]")
        .build();

        // 请求添加请求体
        builder.put(formBody);

        // 继续进行这个请求
        return chain.proceed(builder.build());
        }
        */
        }

4.自定义RetrofitManage整体代码展示
package com.demon.retrofit20.http;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author Demon
 * @version V1.0
 * @Description: Retrofit2.0 管理类
 * @date 2016年10月13日11:22:43
 */
public class RetrofitManage {

    /**
     * HTTP 请求地址
     **/
    private final String API_URL = "http://192.168.1.100/apiServer/";
    /**
     * 网络请求api
     */
    private RetrofitService api;

    private static RetrofitManage retrofitManage = null;

    /**
     * 静态工厂方法(单例)
     *
     * @return RetrofitManage
     */
    public synchronized static RetrofitManage getInstance() {
        if (retrofitManage == null) {
            retrofitManage = new RetrofitManage();
        }
        return retrofitManage;
    }

    /**
     * 构造方法
     */
    private RetrofitManage() {
        // 实例化授权拦截器
        OAuthInterceptor authInterceptor = new OAuthInterceptor(null, null);

        // OkHttp3 配置
        OkHttpClient client = new OkHttpClient.Builder()
                // 添加拦截器
                .addInterceptor(authInterceptor)
                // 连接超时时间
                .connectTimeout(7676, TimeUnit.SECONDS)
                // 读取时间
                .readTimeout(7676, TimeUnit.SECONDS)
                .build();

        // addInterceptor : 设置应用拦截器,可用于设置公共参数,头信息,日志拦截等
        // connectTimeout : 设置超时时间
        // readTimeout : 设置读取时间

        // 需添加依赖 'com.squareup.retrofit2:retrofit:2.1.0'
        Retrofit retrofit = new Retrofit.Builder()
                // 服务器请求URL
                .baseUrl(API_URL)
                // 添加Gson转换器 需添加依赖 'com.squareup.retrofit2:converter-gson:2.1.0'
                .addConverterFactory(GsonConverterFactory.create())
                // OkHttp3 对象
                .client(client)
                .build();

        // 获取Proxy.newProxyInstance动态代理对象
        api = retrofit.create(RetrofitService.class);
    }

    /**
     * 外部获取 RetrofitService
     * @return
     */
    public RetrofitService getApi() {
        return api;
    }
}

二、编写接口RetrofitService 常用方法

1.常用方法编写
  • 数据请求

      /**
       * 个人信息(改造前)
       * @param     userId 用户Id
       * @return     ResponseBody
       */
      @POST("userInfo")
      Call userInfoB(@Query("userId") String userId);
    
  • 上传文件

      /**
       * 上传文件(改造前)
       * @param makeThum String
       * @param file MultipartBody.Part
       * @return ResponseBody
       */
      @Multipart
      @POST("http://192.168.1.1/recycleImgServer/uploadFile")
      Call uploadFileB(@Query("makeThum")String makeThum, @Part MultipartBody.Part file);
    
2.完整代码展示
package com.demon.retrofit20.http;

import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Query;

/**
 * @author Demon
 * @version 1.0
 * @Description Retrofit 2.0 网络请求API
 * @date 2016年10月13日13:54:01
 */
public interface RetrofitService {

    /**
     * 个人信息(改造前)
     * @param     userId 用户Id
     * @return     ResponseBody
     */
    @POST("userInfo")
    Call userInfoB(@Query("userId") String userId);

    /**
     * 上传文件(改造前)
     * @param makeThum String
     * @param file MultipartBody.Part
     * @return ResponseBody
     */
    @Multipart
    @POST("http://192.168.1.1/recycleImgServer/uploadFile")
    Call uploadFileB(@Query("makeThum")String makeThum, @Part MultipartBody.Part file);

}

三、RetrofitService调用

1.RetrofitService获取
/**
 * 网络请求API对象
 */
private RetrofitService api;

private void initHttp() {
    api = RetrofitManage.getInstance().getApi();
}
3.同步请求
Repo repo = call.execute();

以上的代码会阻塞线程,不能在安卓的主线程中调用,不然会NetworkOnMainThreadException。
如果想调用execute方法,请在后台线程执行。

2.异步请求
/**
 * 获取个人信息(改造前)
 */
private void userInfoB() {
    // 调用接口方法
    Call call = api.userInfoB("103");
    // 异步请求
    call.enqueue(new Callback() {
        // 异步请求 需要Callback回调
        @Override
        public void onResponse(Call call, Response response) {
            Toast.makeText(getApplicationContext(), response.body().toString(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
        }
    });

    // 关闭请求
    // call.clone();
    // call只能调用一次。否则会抛 IllegalStateException

    // 取消
    // call.cancel();
}

2016/10/19 00:58:32
代码地址

你可能感兴趣的:(Retrofit 2.1 笔(基础))