retrofit网络请求框架——简单教程

一、配置

compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:converter-gson:2.4.0'
 //该网络框架本质上还是okhttp网络请求,所以需要添加okhttp的依赖
compile 'com.squareup.okhttp3:okhttp:3.11.0' 

二、实体类建立

根据返回的数据格式进行建立对应的实体类,注,每个属性应该是public

三、网络接口建立

public interface HttpRequest {
//此处@GET表示请求类型,可为@POST; @Query("xxx") <type> xxx 表示请求参数
//例:teacher?type=4&num=30,  "?"之前为GET("...")中需要填的,之后是请求参数,如果是动态的可填写到方法参数中作为形参
	@GET("teacher")
	Call<Data> getCall(@Query("type") int type, @Query("num") int num);
	
	//@Path URL地址的缺省值 
	//例:  发送请求时{user}会被替换成方法的对应参数user
	@GET("users/{user}/repos")
		Call<Model> getData(@Path("user") String user);

//@POST请求,常用情况,这里使用参数要添加@Field
@POST("bbs/label")
@FormEncoded
Call<Model> postLabel(@Field("name") String name, @Field("id")int id);
}

注:上面的Model或Data为服务器端返回的数据bean,retrofit网络框架会自动将返回的数据解析成该数据bean

四、创建Retrofit对象并设置数据解析器

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://www.imooc.com/api/")//设置网络请求的url地址
            .addConverterFactory(GsonConverterFactory.create())//设置数据解析器
            .build();

五、生成接口对象

HttpRequest httpRequest = retrofit.create(HttpRequest.class);

六、调用接口方法返回call对象

final retrofit2.Call<Data> call = httpRequest.getCall(type,num);

七、发送网络请求

    //同步
   /* new Thread(new Runnable() {
        @Override
        public void run() {
            Response<Data> response = null;
            try {
                response = call.execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //处理服务器返回的数据
            showData(response.body());
        }
    }).start();
    */

    //异步(推荐)
    call.enqueue(new retrofit2.Callback<Data>() {
        @Override
        public void onResponse(retrofit2.Call<Data> call, retrofit2.Response<Data> response) {
            //处理结果
            final Data data = response.body();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (data!=null)
                        showData(data);
                    swipeRefresh.setRefreshing(false);
                }
            });
        }

        @Override
        public void onFailure(retrofit2.Call<Data> call, Throwable t) {
            t.printStackTrace();
            Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
        }
    });

总结

这只是很简单retrofit网络请求框架的认识,它简化了okhttp请求,但在使用上仍然有所不便,我们还可以根据自己的需求进行相应的封装简化,其核心步骤就是这几步而已。

猜你喜欢

转载自blog.csdn.net/qq_39734865/article/details/88788936