定义接口 public interface ApiService { /** * 获取服务器时间 * @return */ @GET("serverTime.json") Observable<ServerTimeResBean> getServerTime(); }
//HttpManager public class HttpManager { private static final String BASE_URL = "https://XXX.com/"; private static HttpManager INSANCE; private ApiService apiService;; public static HttpManager getInstance(){ if(INSANCE == null){ synchronized (HttpManager.class){ if(INSANCE == null){ INSANCE= new HttpManager(); } } } return INSANCE; } private HttpManager(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(new OkHttpClient.Builder() .connectTimeout(15L, TimeUnit.SECONDS)//设置超时时间 .retryOnConnectionFailure(true) .addInterceptor(new CommonInterceptor()).build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); apiService = retrofit.create(ApiService.class); } public ApiService getApiService(){ return apiService; } }
//拦截器,可以打印日志,或者修改接口参数,加请求头
public class CommonInterceptor implements Interceptor { private static final String TAG = "CommonInterceptor"; @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //可以修改参数 ... Response response = chain.proceed(request); HttpUrl url = request.url(); Charset charset; charset = Charset.forName("UTF-8"); ResponseBody responseBody = response.peekBody(Long.MAX_VALUE); Reader jsonReader = new InputStreamReader(responseBody.byteStream(), charset); BufferedReader reader = new BufferedReader(jsonReader); StringBuilder sbJson = new StringBuilder(); String line = reader.readLine(); do { sbJson.append(line); line = reader.readLine(); } while (line != null); //打印接口日志 Log.e(TAG, "method :" + request.method() + " ,url:"+ url +" ,response: " + sbJson); return response; } }
//接口调用:
HttpManager.getInstance().getApiService().getServerTime() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()).subscribe(new Consumer<ServerTimeResBean>() { @Override public void accept(ServerTimeResBean serverTimeResBean) throws Exception { Toast.makeText(MainActivity.this, "get server time:" + gson.toJson(serverTimeResBean), Toast.LENGTH_SHORT).show(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Log.e(TAG, "error: -->>" + throwable.toString()); } });
引入库:
implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0' // 用Gson解析json的转换器 implementation 'com.google.code.gson:gson:2.8.5' //rxjava2 implementation 'io.reactivex.rxjava2:rxandroid:2.1.0' implementation 'io.reactivex.rxjava2:rxjava:2.2.5'