妹子图APP(一)—— Retrofit+Glide+Gson加载网络图片

网络请求:Retrofit    地址: https://github.com/square/retrofit
图片加载:Glide       地址: https://github.com/bumptech/glide
数据解析:Gson
1.添加依赖:
Retrofit
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依赖包
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依赖包
Glide 
//工程的build.gradle文件中
repositories {
    mavenCentral() 
}
//Module的build.gradle文件中
dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:19.1.0'
}
网络请求需要权限
    <uses-permission android:name="android.permission.INTERNET"/>
2.准备数据
图片数据来源:易源数据( https://www.showapi.com/)300次每天
http://route.showapi.com/197-1?showapi_appid=34276&showapi_sign=731d68d6d56b4d789d6571f530ee28ef&num=10
请求地址分为几部分:
    https://www.showapi.com/ //接口基地址
    197-1 //接口地址
    showapi_appid //易源应用ID
    showapi_sign  //身份验证
    num  //每页返回的数据条数
    page //页数(非必须)
访问上述网址,获得Json数据,使用Gson的GsonFormat插件将Json数据转换为GirlBean对象
3.Retrofit的使用
@Query、@QueryMap://用于Http Get请求传递参数
@Field://用于Post方式传递参数,需要在请求接口方法上添加@FormUrlEncoded,即以表单的方式传递参数
@Body: //用于Post,根据转换方式将实例对象转化为对应字符串传递参数.
        //比如Retrofit添加GsonConverterFactory则是将body转化为gson字符串进行传递
@Path: //用于URL上占位符
@Part: //配合@Multipart使用,一般用于文件上传
@Header://添加http header
@Headers://跟@Header作用一样,只是使用方式不一样,@Header是作为请求方法的参数传入,@Headers是以固定方式直接添加到请求方法上POST请求
3.1自定义请求接口
public interface ApiService {

    @POST("197-1")
    @FormUrlEncoded
    Call<GirlBean> getGirls(@Field("showapi_appid") String showapi_appid,
                               @Field("showapi_sign") String showapi_sign,
                               @Field("num") int num ,
                               @Field("page") int page);
//    //GET请求
//    @GET("197-1")
//    Call<GirlBean> getGirls(@Query("showapi_appid") String showapi_appid,
//                            @Query("showapi_sign") String showapi_sign,
//                            @Query("num") int num ,
//                            @Query("page") int page);

}
3.2请求数据
定义一个类,用于Retrofit请求数据
public class GirlsRequest {
    public static final String baseurl = "http://route.showapi.com/";
    public static final String showapi_appid = "34276";
    public static final String showapi_sign = "731d68d6d56b4d789d6571f530ee28ef";
    public static final int num = 10;

    //创建Retrofit对象
    Retrofit mRetrofit = new Retrofit.Builder()
            .baseUrl(baseurl)//请求基地址
            //添加转换器,直接将内容转换成String或者json
            //.addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    public void getGirlList(final RequsetCallback requsetCallback, int page) {
        //创建请求的接口
        ApiService mApiService = mRetrofit.create(ApiService.class);
        Call<GirlsBean> mCall = mApiService.getGirls(showapi_appid,showapi_sign,num,page);
        //利用Call对象,发起网络请求
        mCall.enqueue(new Callback<GirlsBean>() {
            //请求成功
            @Override
            public void onResponse(Call<GirlsBean> call, Response<GirlsBean> response) {
                //成功获得正确数据
                if (response.body().getShowapi_res_code() == 200) {
                    requsetCallback.onFinish(response.body());
                } else {
                    //错误数控
                    requsetCallback.onError(response.body().getShowapi_res_error());
                }
            }
            //失败
            @Override
            public void onFailure(Call<GirlsBean> call, Throwable t) {
                requsetCallback.onError("网络请求失败");
            }
        });
    }
    //自定义回调接口
    public interface RequsetCallback<T>{
        void onFinish(T data);

        void onError(String msg);
    }
}
4.显示数据
         a).网络加载图片到ImageView中
Glide.with(context).load(imageUrl).into(imageView);
         b). 当加载网络图片时,由于加载过程中图片未能及时显示,此时可能需要设置等待时的图片
Glide.with(context).load(imageUrl).placeholder(R.mipmap.ic_launcher).into(imageView);
         c). 当加载图片失败时,通过error(Drawable drawable)方法设置加载失败后的图片显示
Glide.with(context).load(imageUrl).error(R.mipmap.ic_launcher).into(imageView);
图片列表使用RecyclerView 实现
在适配器中的onBindViewHolder方法中使用Glide设置图片
    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        //Glide设置图片(未加载则用粉色替代)
        Glide.with(mContext)
                .load(mList.get(position).getPicUrl())
                .centerCrop()
                .placeholder(R.color.colorAccent)
                .into(holder.mImageView);
    }
5.完成加载图片的功能
public class MainActivity extends AppCompatActivity implements 
        GirlsRequest.RequsetCallback<GirlsBean>{

    private  RecyclerView mRecyclerView;
    private MyAdapter mAdapter;
    private GridLayoutManager mGridLayoutManager;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        //RecyclerView 设置行列
        mGridLayoutManager = new GridLayoutManager(this,2);
        //VERTICAL代表有多少列,HORIZONTAL就代表有多少行,
        mRecyclerView.setLayoutManager(mGridLayoutManager);

        GirlsRequest request = new GirlsRequest();
        //调用getGirlList方法请求数据
        request.getGirlList(this,1);
    }

    @Override
    public void onFinish(GirlsBean data) {
        //得到适配器
        mAdapter = new MyAdapter(this,data.getShowapi_res_body().getNewslist());
        //设置适配器
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onError(String msg) {
        //吐司错误信息
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }
}
暂时的效果

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值