OkHttp+Retrofit 简单使用

此篇适合伸手党(工作经验超过一年者请绕路)

添加依赖

/*Retrofit依赖*/
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

/*OKhttp3依赖*/

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

一、定义OkRetrofitUtil工具类

其实就是一个普通的java类,其中有一些全局变量。

public class OkRetrofitUtil {
    public static OkHttpClient client;
    public static Retrofit retrofit;

    /* 私有化构造方法 * 使用单利模式 */
    private OkHttpUtil() { }

二、定义OkRetrofitUtil的init方法

这个init()方法是让我们在项目的初始化时候调用的,作用是实利化OkHttpClient对象,传入公共的请求头参数。

    public static void init() {

        client = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.MILLISECONDS)
                .writeTimeout(3000, TimeUnit.MILLISECONDS)
                .readTimeout(3000, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(true)  //如果连接失败尝试重连
                .build();
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl("http://172.17.8.100/small/")  //baseUrl是放入我们接口的基础地址,并不是固定的,根据你的接口而改变
                .client(client)
                .build();
    }
 

三、写一个接口,拼接参数和请求方法

/*

扫描二维码关注公众号,回复: 4991584 查看本文章

* * @GET("基础路径后面的部分")Get请求方法,根据要求变动

* @Headers 请求头使用该注解

* @Query 普通参数使用此注解

 */

public interface LoginService {

    @GET("user/v1/login") 
    Call<LoginBean> getData(@Header("userId") int userId,@Query("page") int page);

}

四、使用方式

首先要在项目的application中调用init方法

首先要在项目的application中调用init方法

首先要在项目的application中调用init方法

重要的事情说三遍 ! ! !


        LoginService loginService = OkHttpUtil.retrofit.create(LoginService.class);
        Call<LoginBean> call = loginService.getData(userId, page);

        //异步请求
        call.enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {

               //获取服务器返回的数据
                LoginBean loginBean= response.body();
            }
            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
            }
        });

猜你喜欢

转载自blog.csdn.net/qq_42809182/article/details/84885623