美文网首页
记录一下Retrofit

记录一下Retrofit

作者: 阿飞爱吃水果 | 来源:发表于2018-04-16 12:39 被阅读0次

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.创建一个接口类(比如下图)

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

      本文链接:https://www.haomeiwen.com/subject/ztuszxtx.html