写在前面的话:习惯性AS开发,初涉,目前状态和要求是能用他两完成网络请求、json数据转换。
需要导入的包:
compile 'com.squareup.retrofit2:retrofit:latest.integration' compile 'com.squareup.okhttp3:okhttp:latest.integration' compile 'com.squareup.okio:okio:latest.integration' compile 'com.squareup.retrofit2:converter-gson:latest.integration' compile 'com.google.code.gson:gson:latest.integration'导入 converter-gson是需要retrofit直接给我们转换返回的json数据,不用我们获取json字符串什么的再去手动写代码转换,而这里同时需要导入对应的gson包。
1、初始化okhttp:
这里的初始化根据自己项目需求设置,这里增加了头信息,设置了链接失败重连机制,最多重连3次,可以根据需要更改。
//初始化 OkHttpClient OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间 .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间 int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(MyApplication.getInstance().getCacheDir(), cacheSize); builder.cache(cache); // 拦截器 builder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("apikey", "").build(); // 请求连接 Response response = chain.proceed(request); int tryCount = 0; //连接失败,最多重复三次 while (!response.isSuccessful() && tryCount < 3) { tryCount++; response = chain.proceed(request); } return response; } }); OkHttpClient client = builder.build();2、初始化retrofit:
这里有一个全局常量BASE_URL,这是请求的基础链接地址,还有一个service变量,存储获取到的接口文件实例化对象,属性可以根据自己的接口文件名更改,这里是APIService。这里建议接口写在一个文件里,当然,前提是接口不是特别多的情况下,如果几十个,建议还是分开,这里只写一个文件的例子。
Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(APIService.class);3、开放一个方法给外部调用接口对象service:
public APIService getService() { return service; }4、请求网络:
我这里请求的是图片接口,返回一个res类,里边的格式是{status:true,message:OK,result:[{},{}]},所以定义了Response类来接收数据,给了一个泛型,说明result里的是一个数组,数组内容跟ImageValue里的变量对应。
Call<ResponseValue<ArrayList<ImageValue>>> call = HttpUtil.getInstance().getService().loadImages(); call.enqueue(new Callback<ResponseValue<ArrayList<ImageValue>>>() { @Override public void onResponse(Call<ResponseValue<ArrayList<ImageValue>>> call, retrofit2.Response<ResponseValue<ArrayList<ImageValue>>> response) { ResponseValue<ArrayList<ImageValue>> rv = response.body(); Log.i("", "response---->成功" ); } @Override public void onFailure(Call<ResponseValue<ArrayList<ImageValue>>> call, Throwable t) { Log.e("", "response----失败:" + t.getLocalizedMessage()); } });
到这里,请求基本完成了,数据返回后在onResponse里进行处理,比如取出list,放到adapter里什么的,这里就不写了。
最后附上APIService:
public interface APIService { @GET("news") Call<ResponseValue<ArrayList<ImageValue>>> loadImages(); @GET("show") Call<ImageValue> loadImageDetails(@Query("id") int id); }