OkHttp+Retrofit

1.依赖 

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
//ConverterFactory的Gson依赖包
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
//ConverterFactory的String依赖包
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
implementation 'com.squareup.okio:okio:1.11.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.0.2'

2.util

public class RetrofitUtl {
    public static OkHttpClient okHttpClient;
    public static RetrofitUtl instance;
    public static RetrofitService retrofitService;

    private RetrofitUtl() {
    }

    public static RetrofitUtl getInstance() {
        return instance;
    }

    public static void init() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("")
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        retrofitService = retrofit.create(RetrofitService.class);

    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(1000, TimeUnit.MILLISECONDS)
                    .connectTimeout(1000, TimeUnit.MILLISECONDS)
                    .build();
        }
        return okHttpClient;
    }
}

3.service

public interface RetrofitService {

    @GET("group_user.php?act=group_index")
    Call getMessage();

    @FormUrlEncoded
    @POST
    Call getMessagePost(@Field("token") String token);
}

你可能感兴趣的:(Android)