marco de solicitud de red de actualización: tutorial simple

1. Configuración

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. Creación de clases de entidad.

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

3. Establecimiento de interfaz de red.

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

Nota: El modelo o datos anterior es el bean de datos devuelto por el servidor. El marco de red de actualización analizará automáticamente los datos devueltos en el bean de datos.

4. Cree un objeto Retrofit y configure el analizador de datos.

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

5. Generar objetos de interfaz

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

6. Llame al método de interfaz y devuelva el objeto de llamada.

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

7. Enviar solicitud de red

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

Resumir

Esta es solo una comprensión muy simple del marco de solicitud de red de actualización. Simplifica la solicitud okhttp, pero aún es inconveniente de usar. También podemos simplificar el empaquetado de acuerdo con nuestras propias necesidades. Los pasos principales son solo estos pasos.

Supongo que te gusta

Origin blog.csdn.net/qq_39734865/article/details/88788936
Recomendado
Clasificación