Retrofit学习记录

Retrofit

retrofit框架是对OKhttp进行了封装的网络请求框架,通过注解的形式来构建请求。

Retrofit的基本使用

添加依赖
implementation 'com.squareup.retrofit2:retrofit:2.7.1'
生明一个接口类
public interface TestAPI {
    @GET("/get/text")
    Call<ResponseBody> getJson();
}
创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.102:9102")
                .build();

这里传入的baseUrl和接口中注解的路径拼接后才形成完整的URL

进行网络请求
TestAPI api = retrofit.create(TestAPI.class);
        Call<ResponseBody> task = api.getJson();
        task.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.code() == 200){
                    try {
                        assert response.body() != null;
                        Log.i(TAG, "onResponse: " + response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });

通过retrofit的create方法创建TestAPI对象之后调用在接口中声明的GET方法获取到Call对象,调用call的enqueue方法执行请求,在Callback中进行返回数据的处理。
运行后就可以看到后台输出下面的json,表示网络请求成功

onResponse: {"success":true,"code":10000,"message":"获取成功","data":[{"id":"1214469820037255168","title":"Android加载大图片,解决OOM问题","viewCount":244,"commentCount":23,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/10.png"},{"id":"1214469820045643776","title":"Volley/Xutils对大图片处理算法源码分析","viewCount":82,"commentCount":88,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/14.png"},{"id":"1214469820045643777","title":"Android开发网络安全配置","viewCount":168,"commentCount":78,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/11.png"},{"id":"1214469820045643778","title":"Android开发网络编程,请求图片","viewCount":272,"commentCount":88,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/3.png"},{"id":"1214469820045643779","title":"Intent页面跳转工具类分享","viewCount":209,"commentCount":63,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/3.png"},{"id":"1214469820045643780","title":"阳光沙滩商城的API文档","viewCount":64,"commentCount":45,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/5.png"},{"id":"1214469820045643781","title":"Android课程视频打包下载","viewCount":314,"commentCount":27,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/12.png"},{"id":"1214469820045643782","title":"非常轻量级的gif录制软件","viewCount":173,"commentCount":56,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/10.png"},{"id":"1214469820045643783","title":"Fiddler抓包工具,墙裂推荐,功能很强大很全的一个工具","viewCount":193,"commentCount":26,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/2.png"},{"id":"1214469820045643784","title":"AndroidStudio奇淫技巧-代码管理","viewCount":167,"commentCount":59,"publishTime":"2020-01-07T08:52:23.514+0000","userName":"程序员拉大锯","cover":"/imgs/1.png"},{"id":"1214469820045643785","title":"OC和Swift混编","viewCount":113,"commentCount":61,"publishTime":"2020-01-07T08:52:23.515+0000","userName":"程序员拉大锯","cover":"/imgs/11.png"},{"id":"1214469820049838080","title":"最新的Android studio是不是没有Android Device Monitor","viewCount":94,"commentCount":31,"publishTime":"2020-01-07T08:52:23.515+0000","userName":"程序员拉大锯","cover":"/imgs/7.png"}]}
GsonConverterFactory

在构建Retrofit对象的时候可以为Retrofit添加类型转化的工厂类,可以实现call的返回直接就是Bean对象。
添加依赖

implementation 'com.squareup.retrofit2:converter-gson:2.7.1'

将接口中的GET方法的返回进行修改

public interface TestAPI {
    @GET("/get/text")
    Call<TestModel> getJson();
}

TestModel类为一个JAVABean对象
进行网络请求

 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.102:9102")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        TestAPI api = retrofit.create(TestAPI.class);
        Call<TestModel> task = api.getJson();
        task.enqueue(new Callback<TestModel>() {
            @Override
            public void onResponse(Call<TestModel> call, Response<TestModel> response) {
                if(response.code() == 200){
                    TestModel testModel = response.body();
                    assert testModel != null;
                    mAdapter.setDataBeanList(testModel);
                }
            }
            @Override
            public void onFailure(Call<TestModel> call, Throwable t) {
                t.printStackTrace();
            }
        });
使用带参数的GET请求

接口类中的GET方法

@GET("/get/param")
    Call<WithParamModel> getWithParam(@Query("keyword")String keyword, @Query("page") int page, @Query("order")String order);

下面用RetrofitManager类封装了一下Retrofit对象的创建。进行有参数的GET请求只要在调用方法时对应传参就行

Retrofit retrofit = RetrofitManager.getRetrofit();
        TestAPI api = retrofit.create(TestAPI.class);
        Call<WithParamModel> task = api.getWithParam("关键字", 10, "1");
        task.enqueue(new Callback<WithParamModel>() {
            @Override
            public void onResponse(Call<WithParamModel> call, Response<WithParamModel> response) {
                Log.i(TAG, "onResponse: " + response.body());
            }

            @Override
            public void onFailure(Call<WithParamModel> call, Throwable t) {
                Log.e(TAG, "onFailure: 出现错误",t);
            }
        });
使用QueryMap传递多个参数
@GET("/get/param")
    Call<WithParamModel> getWithParam(@QueryMap Map<String,Object> params);

使用QueryMap后参数就会变成Map集合

Post请求

进行POST请求的方式和GET基本一致
主要是将原本的注解从GET换成POST,其他操作基本一样

@POST("/post/string")
    Call<PostStringModel> postWithParam(@Query("string")String content);
POST提交JSON

POST提交json数据我们可以将json封装成对应的bean类之后通过@Body注解参数进行传递

@POST("/post/json")
    Call<PostStringModel> postWithJson(@Body TestModel model);
表单的方式提交

使用表单的方式提交需要在方法添加一个@FormUrlEncoded注解
然后在方法的参数使用@Field表示每个表单项。

@POST("/post/form")
    @FormUrlEncoded
    Call<PostStringModel> postWithForm(@Field("username") String name,@Field("password")String password);
Retrofit下载文件
@Streaming
    @GET
    Call<ResponseBody> getFile(@Url String fileUrl);

@streaming用于请求的是大文件小文件可以不用
fileUrl是文件的路径或下载地址

Retrofit上传文件

上传文件时会用到@Multipart注解
以下是学习时别人出的事例(由于还没有真实用过只有用学习时的案例)

@Multipart
@POST("user/followers")
Call<ResponseBody> getPartData(@Part("name") RequestBody name, @Part MultipartBody.Part file);
//声明类型,这里是文字类型
 MediaType textType = MediaType.parse("text/plain");
//根据声明的类型创建RequestBody,就是转化为RequestBody对象
RequestBody name = RequestBody.create(textType, "这里是你需要写入的文本:刘亦菲");
 
//创建文件,这里演示图片上传
File file = new File("文件路径");
if (!file.exists()) {
   file.mkdir();
 }
 
//将文件转化为RequestBody对象
//需要在表单中进行文件上传时,就需要使用该格式:multipart/form-data
RequestBody imgBody = RequestBody.create(MediaType.parse("image/png"), file);
//将文件转化为MultipartBody.Part
//第一个参数:上传文件的key;第二个参数:文件名;第三个参数:RequestBody对象
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), imgBody);
 
Call<ResponseBody> partDataCall = retrofit.create(Api.class).getPartData(name, filePart);

添加请求头

@Headers 用于添加固定请求头,可以同时添加多个,通过该注解的请求头不会相互覆盖,而是共同存在
@Header 作为方法的参数传入,用于添加不固定的header,它会更新已有请求头,通过该注解添加的请求头不会相互覆盖,而是共同存在
@Headers 是在方法前注解,是固定的请求头
@Header是方法的参数,可以动态添加不同的请求头
可以根据需要自由选择

@Headers({"Accept-Language:zh-CN,zh;q=0.9"})
    @GET
    Call<ResponseBody> getData(@Header("token") String token);

其他暂时没有用到,等以后再添加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值