Retrofit2.1用法(一)

写博客只是为了方便记忆,希望自己能够坚持下去。

本文只是为了方便自己记忆,想了解的可以通过下面的链接学习。

官方文档 http://square.github.io/retrofit/
github地址 https://github.com/square/retrofit

测试接口 http://v.juhe.cn/toutiao/index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe
数据返回的格式
Retrofit2.1用法(一)_第1张图片

GET方式

一般请求方式
定义接口,用于解析请求数据

public interface HttpService {
    @GET("index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe")
    Call<Result> testHttpGet();


    // GSON - BEAN
    class Result {
        String reason;
        result result;


        class result {
            String stat;
            ArrayList<data> data;


            class data {
                String title;
                String date;
                String author_name;
                String thumbnail_pic_s;
                String thumbnail_pic_s02;
                String url;
                String uniquekey;
                String type;
                String realtype;

            }
        }


    }
}

请求数据

void textGet() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        Call<HttpService.Result> call = service.testHttpGet();
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {

                Log.d("xxx", response.message());
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }

可以看到Debug信息,数据已经解析下来了。

@Path用法
例如有2个接口地址是这样的

String url = http://v.juhe.cn/eg2/
String url = http://v.juhe.cn/eg1/

可通过@Path方式拼接地址

 @GET("{eg}") Call<Result> testHttpGet(@Path("eg") String toutiao);

请求方式

void textGet() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        Call<HttpService.Result> call = service.testHttpGet("eg1");
        //Call<HttpService.Result> call = service.testHttpGet("eg2");
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {

                Log.d("xxx", response.message());
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }

这种方式主要是为了解耦!
(注:地址的拼接不能拼接参数,所以这里只是模拟一下用法,此方法只对真实数据接口有用。)

@Query用法(GET与POST方式都可使用)
测试接口地址
http://v.juhe.cn/toutiao/index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe

可通过Query方法查询参数

@GET("index")
Call<Result> testHttpGet_query(@Query("type") String type, @Query("key") String key);

请求方式

void textGet_query() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);

        Call<HttpService.Result> call = service.testHttpGet_query("top","9e05423f7ac6acf6d0dce3425c4ea9fe");
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
               Log.d("xxx", response.message());

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }

@QueryMap用法
接口地址http://v.juhe.cn/toutiao/index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe

@GET("index")
Call<Result> testHttpGet_ueryMap(@QueryMap HashMap<String, String> map);
void textGet_queryMap() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        HashMap<String,String> map=new HashMap<>();
        map.put("type","top");
        map.put("key","9e05423f7ac6acf6d0dce3425c4ea9fe");
        Call<HttpService.Result> call = service.testHttpGet_ueryMap(map);
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {

                Log.d("xxx", response.message());
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }




POST方式

@Query用法参考GET的@Query用法

@Body用法(接口不支持此方式,下面模拟用法)
用于POST上传json数据
例如接口是这样的

String url = http://v.juhe.cn/toutiao/

需要上传json数据,才能获取到数据

{"type":"xxx","key":"xxx"}
@POST("toutiao")
Call<Result> testHttpPost(@Body Params params);

class Params {
        String type;
        String key;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public Params(String type, String key) {
            this.type = type;
            this.key = key;
        }
    }

Result类上文已给出

请求数据

void textPost_body() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);

        Call<HttpService.Result> call = service.testHttpPost_body(new HttpService.Params("top","9e05423f7ac6acf6d0dce3425c4ea9fe"));
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                Log.d("xxx", response.body().reason);
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {

            }
        });

    }

@Field用法

@FormUrlEncoded @POST("index") Call<Result> testHttpPost_formUrlEncoded(@Field("type") String type, @Field("key") String key);
 void textPost_formUrlEncoded() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
       Call<HttpService.Result> call = service.testHttpPost_formUrlEncoded("top","9e05423f7ac6acf6d0dce3425c4ea9fe");
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                list = response.body().result.getData();
                updateUi();

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }

@FieldMap用法

@FormUrlEncoded @POST("index") Call<Result> testHttpPost_formUrlEncoded_map(@FieldMap HashMap<String, String> map);
void textPost_formUrlEncoded_map() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "top");
        map.put("key", "9e05423f7ac6acf6d0dce3425c4ea9fe");
        Call<HttpService.Result> call = service.testHttpPost_formUrlEncoded_map(map);
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                list = response.body().result.getData();
                updateUi();

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }

编码方式

在使用POST方式时, 如果出现乱码,则需要对中文进行编码。

//可以通过此方法进行编码 
 String type =  URLEncoder.encode("头条","UTF-8");

@Headers用法
可直接通过Headers设置编码格式

@Headers("Content-type:application/x-www-from-urlencoded;charset=UTF-8")
@FormUrlEncoded
@POST("index")
Call<Result> testHttpPost_formUrlEncoded_map_headers(@FieldMap HashMap<String, String> map);

@Header用法

@FormUrlEncoded @POST("index") Call<Result> testHttpPost_formUrlEncoded_map_header(@Header("Content-Type") String contentType,@FieldMap HashMap<String, String> map);
void textPost_formUrlEncoded_map_header() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "top");
        map.put("key", "9e05423f7ac6acf6d0dce3425c4ea9fe");
        Call<HttpService.Result> call = service.testHttpPost_formUrlEncoded_map_header("Content-type:application/x-www-from-urlencoded;charset=UTF-8",map);
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                list = response.body().result.getData();
                updateUi();

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }

Demo效果图

源码地址

https://github.com/jiangzehui/RetrofitDemo

你可能感兴趣的:(retrofit)