Retrofit(原意:改进,改良)是Square公司开源的一个高质量高效率的http库,目前非常流行的网络框架,效率高,实现简单。运用注解和动态代理,极大地简化了网络请求的繁琐步骤。
特点是:
性能好,处理快,使用简单,目前最流行的HTTP Client库之一使用REST API非常方便支持NIO(新的IO API,可以替代标准的Java IO API)Retrofit默认使用OKHttp处理网络请求默认使用Gson解析1、导入依赖库
第一种:在gradle文件中添加compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
同步后External Libraries中增加:
retrofit-2.0.0-beta4okhttp-3.0.1okio-1.6.0 第二种:在gradle文件中添加compile 'com.squareup.retrofit2:converter-goon:2.0.0-beta4'同步后External Libraries中增加:
retrofit-2.0.0-beta4okhttp-3.0.1okio-1.6.0gson-2.4converter-gson-2.0.0-beta42、Retrofit2中网络访问常用注解接口
@GET GET网络请求方式@POST POST网络请求方式@Headers 头信息参数@Path 路径参数。替换url地址中{}所括的部分@Query 查询参数。将在url地址中追加类似“page=1”的字符串,形成提交给服务器端的请求参数@QueryMap 查询参数集合。在url地址中追加类似“type=text&count=30&page=1”的字符串@FormUrlEncoded 对表单域中填写内容进行编码处理,避免乱码@Field 指定form表单域中每个控件的name及相应数值@FieldMap表单域集合@MultipartPost提交分块请求,如果上传文件,必须指定Multipart@PartPost提交分块请求@BodyPost提交分块请求 3、Retrofit2代码实现步骤 定义一个接口(封装URL地址和数据请求)实例化Retrofit通过Retrofit实例创建接口服务对象接口服务对象调用接口中方法,获得Call对象Call对象执行异步请求 4、GET网络请求中接口的写法4.1无参GET请求方式使用
(1)定义一个接口(封装URL地址和数据请求)public interface MyServerInterface { /** * Get请求无参请求 * @return */ @GET("article/list/latest?page=1")//封装的URL Call<ResponseBody> getlatestJsonString();//自定义方法,返回回调接口Call }(2)实例化Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.URL_BASE)//Constant.URL_BASE = "http://m2.qiushibaike.com/" 在请求时,就会将BaseUrl和@GET中的地址拼接起来 .build();(3)通过Retrofit实例创建接口服务对象MyServerInterface myServerInterface = retrofit.create(MyServerInterface.class);(4)接口服务对象调用接口中方法,获得Call对象Call<ResponseBody> responseBodyCall = myServerInterface.getlatestJsonString();(5)Call对象执行异步请求responseBodyCall.enqueue(new Callback<ResponseBody>() { /** * 请求成功 * @param call * @param response */ @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { try { textView_info.setText(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } /** * 请求失败 * @param call * @param t */ @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } });插曲一:BaseUrl 的拼接方式
插曲二:GET请求,方法中无参,但在@URL里定义了完整的URL路径如下
@GET("http://img.265g.com/userup/1201/201201071126534773.jpg") Call<ResponseBody> getNetworkData(); 这种情况下BaseUrl会被忽略,可以用在下载图片
4.2有参GET请求,方法中指定@Path参数和@Query参数。使用方式
(1)定义一个接口(封装URL地址和数据请求)public interface MyServerInterface { /** * Get请求无参请求 * @return */ @GET("article/list/latest?page=1") Call<ResponseBody> getlatestJsonString(); /** * GET请求 有参请求 * @param type * @param page * @return */ @GET("article/list/{type}?") Call<QiushiModel> getInfoList(@Path("type") String type, @Query("page") int page);//QiushiModel为Model模型 } (2)实例化RetrofitRetrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.URL_BASE) //增加返回值为Gson的支持(以实体类返回) .addConverterFactory(GsonConverterFactory.create()) .build(); (3)通过Retrofit实例创建接口服务对象MyServerInterface myServerInterface = retrofit.create(MyServerInterface.class);(4)接口服务对象调用接口中方法,获得Call对象 Call<QiushiModel> qiushiModelCall = myServerInterface.getInfoList("latest", 1);(5)Call对象执行异步请求 qiushiModelCall.enqueue(new Callback<QiushiModel>() { /** * 请求成功 * @param call * @param response */ @Override public void onResponse(Call<QiushiModel> call, Response<QiushiModel> response) { if(response.isSuccessful()&&response.body()!=null){ List<QiushiModel.ItemsBean> itemsBeen = response.body().getItems(); } } /** * 请求失败 * @param call * @param t */ @Override public void onFailure(Call<QiushiModel> call, Throwable t) { } });4.3GET请求,表单的提交,@QueryMap的使用方式
接口中定义:
/** * GET 请求Map形式参数,形如表单提交 * @param map * @return */ @GET("MyWeb/RegServlet") Call<ResponseBody> getRegInfo(@QueryMap Map<String,String> map); 参数传递:Map<String, String> map = new HashMap<>(); map.put("username", username); map.put("password", pwd); map.put("age", age); Call<ResponseBody> responseBodyCall = myServerInterface.getRegInfo(map); responseBodyCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.isSuccessful()&&response.body()!=null){ try { textView_result.setText(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } });下篇说说Post请求。
谢谢Steven老师!