retrofit在使用过程中所遇到的问题点

retrofit已经出来2年了,网上关于介绍的信息也已经很多了!这里说下我在使用retrofit时所遇到的问题。

第一个问题:导入retrofit相关的依赖存在的问题
问题:More than one file was found with OS independent path ‘META-INF/rxjava.properties’
解决方案:1,一般都会直接过略掉相同存在的文件名,在bulid.gradle中android下添加如下:

   添加packagingOptions {
    exclude 'META-INF/rxjava.properties'
}

具体的排查问题可以参考如下博客:https://blog.csdn.net/qq_24216407/article/details/72842614

解决方案2:我的问题,最后的解决方案是远程依赖全部倒错了,正确的导入一份完整的rxjava retrofit等就可以了

implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.14'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

第二个问题:配合okhttp3,完整的打印出请求的log日志
操作如下:

compile 'com.parkingwang:okhttp3-loginterceptor:latest.integration'
在okHttpClient.Builder中添加拦截器:builder.addInterceptor(new LogInterceptor());

**第三个问题:**java.lang.IllegalArgumentException: Unable to create call adapter for rx.Observable

要在构建Retrofit时指定适配器模式为RxJavaCallAdapterFactory,修改如下: .addCallAdapterFactory(RxJava2CallAdapterFactory.create()),此时在接口interface HttpRequestServer传参时,就不能返回Observable,只能返回Call

第四个问题:找不到RxJavaCallAdapterFactory
解决方案:导入:implementation ‘com.squareup.retrofit2:adapter-rxjava2:2.3.0’

**第五个问题:**java.lang.IllegalArgumentException: Unable to create converter for class cn.xy.unittext.bean.ServiceResultBean
解决方案:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://apis.baidu.com/acman/zhaiyanapi/tcrand/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

少了这句话 addConverterFactory(GsonConverterFactory.create())
加这句话的时候,别忘记导包了。这个文件里面bulid.gradle 导
compile “com.squareup.retrofit2:converter-gson:2.0.2

产生原因:产生的原因就是:在接口在接口interface HttpRequestServer传参时,返回的是具体的对象Observable,可以将实体对象ServiceResultBean修改为ResponseBody

第六个问题:在同一个作用域下,指向不同的接口,动态改变不同的接口,通过注解path来实现,http://192.168.24.154/index.php 其中192.168.24.154就是host域名 index.php指的是不同的接口。代码如下

 @GET("{path}")
    Observable<ServiceResultBean> getRequest(@Path("path") String path, @QueryMap Map<String, String> map );

    @FormUrlEncoded
    @POST("{path}")
    Observable<ServiceResultBean> postRequest( @Path("path") String path, @FieldMap Map<String, String> postMap);

最后附上该项目的地址:
https://github.com/willBars/retrofit

猜你喜欢

转载自blog.csdn.net/willba/article/details/80853989