retrofit network request framework - simple tutorial

1. Configuration

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' 

2. Creation of entity classes

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

3. Establishment of network interface

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);
}

Note: The above Model or Data is the data bean returned by the server. The retrofit network framework will automatically parse the returned data into the data bean.

4. Create Retrofit object and set up data parser

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

5. Generate interface objects

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

6. Call the interface method and return the call object

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

7. Send network request

    //同步
   /* 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();
        }
    });

Summarize

This is just a very simple understanding of the retrofit network request framework. It simplifies the okhttp request, but it is still inconvenient to use. We can also simplify the packaging according to our own needs. The core steps are just these steps.

Guess you like

Origin blog.csdn.net/qq_39734865/article/details/88788936