依赖引入
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
封装
public class RetrofitClient {
private static volatile RetrofitClient retrofitClient;
private Retrofit retrofit;
private OkHttpClient okHttpClient;
private ApiService apiService;
private static final String baseUrl = "https://www.baidu.com/";
private RetrofitClient() {}
public static RetrofitClient getInstance() {
if (retrofitClient == null) {
synchronized (RetrofitClient.class) {
if (retrofitClient == null) {
retrofitClient = new RetrofitClient();
}
}
}
return retrofitClient;
}
private OkHttpClient getOkHttpClient() {
if (null == okHttpClient) {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
okHttpClient.writeTimeoutMillis();
okHttpClient.followRedirects();
}
return okHttpClient;
}
private Retrofit getRetrofit() {
if (null == retrofit) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(getOkHttpClient())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return retrofit;
}
public ApiService getApiService() {
if (null == apiService)
apiService = getRetrofit().create(ApiService.class);
return apiService;
}
}
API接口
public interface ApiService {
@POST("/")
Observable<数据Bean> postBeanData(@Body RequestBody requestBody);
}
使用
String json = new Gson.toJson(数据Bean);
ApiService apiService = RetrofitClient.getInstance().getApiService();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(mediaType, json);
apiService.postBeanData(requestBody).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<SensorBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(SensorBean value) {
Log.e("api", "上传的数据:" + value.toString());
}
@Override
public void onError(Throwable e) {
Log.e("api", "上传错误信息返回:" + e.toString());
}
@Override
public void onComplete() {
}
});