记录一下Retrofit

1.先添加依赖

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

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

//引入Log拦截器,方便DEBUG模式输出log信息

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

    compile 'com.github.franmontiel:PersistentCookieJar:v1.0.1'


2.创建一个接口类(比如下图)


记录一下Retrofit_第1张图片

3.新建application类

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Gson gson = new GsonBuilder()

                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")

                .create();//使用 gson coverter,统一日期请求格式

        OkHttpClient okHttpClient = new OkHttpClient.Builder()

                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)

                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)

                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)

                .addInterceptor(loggingInterceptor)

                .cookieJar(new PersistentCookieJar(new SetCookieCache(),new SharedPrefsCookiePersistor(this)))

                .build();

        Retrofit retrofit = new Retrofit.Builder()

                .baseUrl(Constant.BASE_URL)

                .addConverterFactory(GsonConverterFactory.create(gson))

                .client(okHttpClient)

                .build();

      HttpApi mApi = retrofit.create(HttpApi.class);

(mApi抽取成静态成员变量,方便直接调用)

4.Get请求如图1

    Post请求如下图(分带参和无参)


记录一下Retrofit_第2张图片

你可能感兴趣的:(记录一下Retrofit)