您的位置:首页 > 理论基础 > 计算机网络

利用Retrofit进行网络访问

2016-09-22 18:36 295 查看
首先要下载Retrofit包,可以直接在build.gradle中写入
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'
在主函数中
对于 普通的get请求 返回的数据为gson解析后的list集合
public void initRetrofit(){Retrofit retrofit=new Retrofit.Builder().baseUrl(Constant.TEABASE_URL)//如果服务器返回的时json格式数据 设置了GsonConverterFactory//实现对对象的转化// 自定义数据解析器 只要解析器继承Converter.Factory即可.addConverterFactory(GsonConverterFactory.create()).build();INewsBiz iNewsBiz=retrofit.create(INewsBiz.class);Call<List<Tea>> call=iNewsBiz.getTeas();call.enqueue(new Callback<List<Tea>>() {@Overridepublic void onResponse(Call<List<Tea>> call, Response<List<Tea>> response) {if(response.isSuccess()){List<Tea> list=response.body();//获取解析后的集合StringBuilder sb=new StringBuilder();for(Tea t:list){sb.append(t.getProduct_cat_name());}tv.setText(sb.toString());}}@Overridepublic void onFailure(Call<List<Tea>> call, Throwable t) {}});}
Constant类中存储的是网络数据的地址
public final static String TEABASE_URL="http://42.120.4.67/api/app/business/";
定义一个接口存放get请求
public interface INewsBiz {/*通过@GET注解标示为get请求 @GET中填写的value和baseUrl指定的地址组成完成的访问路径baseUrl构造retrofit对象时指定*/@GET("category?app_id=161")Call<List<Tea>> getTeas();}
NewsInfo为数据的实体类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息