(8)RxJava2+Retrofit2+OkHttp3系列(Retrofit2-1)

来源:互联网 发布:c 手机软件编程 编辑:程序博客网 时间:2024/05/22 08:22

今天我们就和大家一起学习一下Retrofit2相关知识。

Github:https://github.com/square/retrofit

官网文档:http://square.github.io/retrofit

Gradle配置:

compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'//这个库可以支持到rxjava2.X//compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'//Retrofit现在只支持到rxjava1.XX//ConverterFactory的String依赖包compile 'com.squareup.retrofit2:converter-gson:2.1.0'

说明:我们现在使用了com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0的库,该库支持到rxjava2.x,Retrofit原生adapter库还不支持rxjava2.x。

接口定义

我们先尝试一个简单的url,看如何定义接口和请求:

(1)http://gank.io/api/data/Android/10/1

那我们应该如何是编写本地接口呢?

//http://gank.io/api/data/Android/10/1@GET("api/data/Android/10/1")Call<GankBean> getGankInfo();//如果没有使用转换,可以这样写 Call<ResponseBody> getGankInfo();

仔细分析这个接口的定义,其实,这个接口我们可用这样去拆分:

这里写图片描述

我们来看Retrofit2的请求应该如何写?

(1)同步:

Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://gank.io/")                .addConverterFactory(GsonConverterFactory.create())                .build();Retrofit2Service api = retrofit.create(Retrofit2Service.class);        Call<GankBean> call = api.getGankInfo();try {    //同步调用execute方法    Response<GankBean> bean = call.execute();} catch (IOException e) {    e.printStackTrace();}

(2)异步:

Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://gank.io/")                .addConverterFactory(GsonConverterFactory.create())                .build();Retrofit2Service api = retrofit.create(Retrofit2Service.class);        Call<GankBean> call = api.getGankInfo();//异步调用enqueue方法call.enqueue(new Callback<GankBean>() {            @Override            public void onResponse(Call<GankBean> call, Response<GankBean> response) {                List<GankBean.ResultsBean> info = response.body().results;                Toast.makeText(context, response.body().error + "", Toast.LENGTH_SHORT).show();            }            @Override            public void onFailure(Call<GankBean> call, Throwable t) {            }        });

接下来我们来看看常见的接口定义。

(2)//http://gank.io/api/data/Android/10/1

//http://gank.io/api/data/Android/10/1@GET("api/data/Android/10/{page}")Call<GankBean> getGankInfo(@Path("page") int page);

(3)http://op.juhe.cn/onebox/weather/query?cityname=深圳&key=您申请的KEY

//http://op.juhe.cn/onebox/weather/query?cityname=深圳&key=您申请的KEY@GET("onebox/weather/query?cityname=深圳")Call<GankBean> getWeather(@Query("key") String key);

(4)//http://op.juhe.cn/onebox/weather/query?cityname=深圳&key=您申请的KEY

//http://op.juhe.cn/onebox/weather/query?cityname=深圳&key=您申请的KEY@GET("onebox/weather/query")Call<GankBean> getWeather(@QueryMap Map<String, String> map);

这种请求方法我们举个例子。

Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://op.juhe.cn/")                .addConverterFactory(GsonConverterFactory.create())                .build();Retrofit2Service api = retrofit.create(Retrofit2Service.class);Map<String, String> params = new HashMap<>();params.put("cityname", "深圳");params.put("key", "4ea58de8a7573377cec0046f5e2469d5");Call<GankBean> call = api.getWeather(params);        call.enqueue(new Callback<GankBean>() {            @Override            public void onResponse(Call<GankBean> call, Response<GankBean> response) {            }            @Override            public void onFailure(Call<GankBean> call, Throwable t) {            }        });

以上都是Get请求方法,我们来看一个Post的请求方式。

(5)

@POST("post/new")Call<GankBean> postUser(@Body User user);
Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://op.juhe.cn/")                .addConverterFactory(GsonConverterFactory.create())                .build();        Retrofit2Service api = retrofit.create(Retrofit2Service.class);        User user = new User();        user.id = 1;        user.name = "name";        Call<GankBean> call = api.postUser(user);        call.enqueue(new Callback<GankBean>() {            @Override            public void onResponse(Call<GankBean> call, Response<GankBean> response) {            }            @Override            public void onFailure(Call<GankBean> call, Throwable t) {            }        });

(6)Post提交表单

@Field,@FieldMap:Post方式传递简单的键值对,
需要添加@FormUrlEncoded表示表单提交
Content-Type:application/x-www-form-urlencoded

@FormUrlEncoded@POST("user/edit")Call<Result> editUser(@Field("id") int id, @Field("name") String name);Content-Type:application/x-www-form-urlencoded
api.editUser(1, "liuguilin").enqueue(new Callback<Result>() {        @Override        public void onResponse(Call<Result> call, Response<Result> response) {            if (response.body().getYes() == 0) {                Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();            }        }        @Override        public void onFailure(Call<Result> call, Throwable t) {        }    });

(7)你可以通过使用@Headers注解来设置请求静态头。

@Headers("Cache-Control: max-age=640000")@GET("widget/list")Call<List<Widget>> widgetList();
@Headers({    "User-Agent: Retrofit-Sample-App",    "Content-Type:application/json"})@GET("users/{username}")Call<User> getUser(@Path("username") String username);

Retrofit2的注解大致有以下几种:

  • 方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP列表内容;
  • 标记注解,包含@FormUrlEncoded、@Multipart、@Streaming;
  • 参数注解,包含@Query,@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap;
  • 其他注解,@Path、@Header,@Headers、@Url;

(8)Post上传文件

@Part,@PartMap:用于POST文件上传
其中@Part MultipartBody.Part代表文件,@Part(“key”) RequestBody代表参数
需要添加@Multipart表示支持文件上传的表单,Content-Type: multipart/form-data

@Multipart    @POST("upload")    Call<ResponseBody> upload(@Part("description") RequestBody description,    @Part MultipartBody.Part file);// create RequestBody instance from file    RequestBody requestFile =            RequestBody.create(MediaType.parse("multipart/form-data"), file);

好啦,到这里Retrofit2的基本常用情况我们就大致说完了,其实Retrofit2还有很多内容,比如拦截器等,大家有兴趣的可以自行研究一下,下一节我们在聊聊OkHttp3。

阅读全文
0 0
原创粉丝点击