FUKING APP

Retrofit使用的那些坑

2016-05-17  本文已影响1587人  DarkAndroid

 鉴于目前成熟的网络框架大片出现,虽然目前项目中自己定义的一套网络框架也可以用,但是隐隐还是觉得跟上时代的步伐,采用开源的比较好。之前用过Volley,简单的使用,没有感觉到特别的地方;现在决定采用当下特别火的Retrofit框架,奈何官网的介绍都是基于MVP的例子,而我对MVP的架构理解尚不够透彻,所以找了些中文资料来看,结果还是遇到很多坑。
 首先,庆幸的是换了Android Studio环境,这里可以直接在app的build.gradle文件中依赖Retrofit项目:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.google.code.gson:gson:2.3.1'

 一般都会依赖这三个库,因为涉及对Response的解析,Json等等。

 一般流程是,在项目构建个API包,里面写个APIStores接口,保存请求服务器的方法,这里Retrofit是以注释的方式实现:

public interface TeacherApiStores {   
  @GET("api/question.jsp")   
  Call<ResponseBody> getQuesList(
  @Query("format") String format, 
  @Query("type") int type,                                                                                               
  @Query("category1") int category1,         
  @Query("category2") int category2,  
  @Query("pageNum") int pageNum, 
  @Query("isanswered") int isanswered );
}

 这里遇到了坑…

 看了网上的例子,都是@Path,我就想当然的把所有参数用@Path形式写上了,但是执行请求的时候报错(肯定会报错啊!),不包含@Path参数;遂查资料,换成了@Field,我靠,当然也不对啊!最后找到了这篇这篇,太赞了,应该使用@Query。然后在请求调用的时候这么写:

 Retrofit retrofit = new Retrofit.Builder()      
//这里建议:- Base URL: 总是以/结尾;- @Url: 不要以/开头          
   .baseUrl("http://www.iyuba.com/")      
   .build();
 TeacherApiStores apiStores = retrofit.create(TeacherApiStores.class);
  Call<ResponseBody> call =        
       apiStores.getQuesList("json",3,quesAppType,quesAbilityType,1,-1);
  call.enqueue(new Callback<ResponseBody>() {   
   @Override   
   public void onResponse(Response<ResponseBody> response) {      
     try {         
       Log.i("renzhy", "response=" + response.body().string());      
     } catch (IOException e) {         
       e.printStackTrace();      
     }   
    }   
   @Override   
   public void onFailure(Throwable t) {      
     Log.i("renzhy", "onFailure=" + t.getMessage());  
   }
 });

 当然这里只是简单的请求了一次服务器(请求总算搞对了),接下来还要对服务器返回的内容Response进行解析。

坑我了很久的一个问题:

java.util.zip.ZipException: duplicate entry: 
com/google/gson/annotations/Expose.class

 各种找gson的jar包,但是就是没有找到!
 结果发现是在HeadNewsLib下边,自己坑自己,没话说!

 总结一下,出现java.util.zip.ZipException: duplicate entry: 错误一定是因为build.gradle和libs中引入的jar包冲突导致的。

 在使用logging interceptor的时候,直接报错:

abstract method not implemented  at 
retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java)

 查资料:
 If you are using logging interceptor you also need to properly version that:

compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'

 If you are using LoganSquare you also need:

apt 'com.bluelinelabs:logansquare-compiler:1.3.4'
compile 'com.bluelinelabs:logansquare:1.3.4'
compile 'com.github.aurae.retrofit2:converter-logansquare:1.2.

 但是仍然看不到Log的信息啊!什么情况!

 后来发现是因为华为P7带锁看不到Log,换成小米就可以。

上一篇下一篇

猜你喜欢

热点阅读