Android 网络请求框架之Retrofit 的 详细使用

一.Retrofit的介绍

retrofit同样是一款由Square公司开发的网路库,上次说的okhttp是一种更接近底层通信的一种使用,而现在的retrofit更加简洁,它是侧重于对功能接口的封装。retrofit是在okhttp基础上进一步开发出来的应用层网络通信库,使我们更加好的理解去进行网路请求。Retrofit官方地址是:https://github.com/square/retrofit

二.Retrofit的基础使用

首先先去官网找到最新的依赖,加入到我们的build.gradle中去

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

首先假设我们请求的网页基本域名是 https://www.xxx/
接口有 1.post : https://www.xxx/postName
参数 : name,password
2.get : https://www.xxx/getName
参数 : name, password

接着我们定义一个接口HttpUtils:

public interface HttpUtils {

    @GET("getName")
    Call<ResponseBody> getLoginMessage(@Query("name")String username,@Query("password") String userpassword);


    @POST("postName")
    @FormUrlEncoded
    Call<ResponseBody> postLoginMessege(@Field("name") String username,@Field("password") String userpwd);

}


。。。类中使用方法
        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("https://www.xxx/ ").build();
        HttpUtils httpUtils = retrofit.create(HttpUtils.class);

        Call<ResponseBody> abc = httpUtils.getLoginMessage("123", "abc");

        abc.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
  1. @POST 和 @GET两个注解分别对应我们的post和get方法,@FormUrlEncoded表示我们的post请求是以类似okhttp的表单的形式。特别注意@POST(“posName”)括号里面的参数是我们请求路径中的路径,这里指,https://www.xxx/postName
  2. @GET注解里面对应的是@Query,而@POST注解对应的是@Field
  3. 如果里面参数很多,我们可以分别改写成一个@FieldMap 和@QueryMap,到时候在代码中用map键值对的方式传参数,key值为请求参数名称,value为值
  4. 到这里是否感觉到比okhttp简单了许多,因为retrofit许多request的构造,请求体等东西不需要我们来实现了。
  5. import okhttp3.ResponseBody;
    import retrofit2.Call;
    特别注意我们导包是导入这两个的,千万别导错了,因为okhtt中也有call包。

三.Retrofit的更多注解

1.方法注解

@GET, @POST, @PATH, @PUT, @DELETE,@HEAD,@OPTION,@HTTP

这里就讲一下@HTTP的作用,其他的用的很少就不阐述了,是用来自定义请求方法的。比如我们这里定义一个post请求方法

@HTTP(method = "post", path = "postName",hasbody = true)
    Call<ResponseBody> getLoginMessage1(@Query("name")String username,@Query("password") String userpassword);

2.标记注解

@FormUrlEncoded , @Multipart, @Streaming

@FormUrlEncoded 该注解是表单提交,对应@POST使用

@Multipart是我们上传文件的时候需要用到的,文章后面会讲到

@Streaming 是我们下载文件的时候用流的方式,避免内存溢出的一个注解

3.参数注解

@Query,@QueryMap,@Field,@FieldMap,@Body,@Part,@PartMap

前四个就是用来表示我们的参数的,这里示范一下我们的QueryMap

@GET("getName")
Call<ResponseBody> getLoginMessage2(@QueryMap Map<String,String> map);

@Body是我们自己来创建类似okhttp里面的FormBody

@GET("getName")
 Call<ResponseBody> getLoginMessage3(@Body ResponseBody body);

使用类中:
...
Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("https://www.xxx/ ").build();
HttpUtils httpUtils = retrofit.create(HttpUtils.class);
RequestBody body = new FormBody.Builder()
                            .add("username","111")
                            .add("pwd","222")
                            .build();
Response response = httpUtils.getLoginMessage3(body).execute();
...

4.其他注解

@Path,@Header,@Headers,@Url

@Path注解是往url地址中动态加入我们的参数,这里假如我们传入的id是1,则我们请求的地址是
https://www.xxx/getName/1?name=username&password=userpassword

@GET("getName/{id}")
 Call<ResponseBody> getLoginMessage4(@Path("id") String nameID,@Query("name")String username,@Query("password") String userpassword);

@Header注解也就是往我们的请求url中添加头部信息,使用方法一样的。而@Headers也是一样的,是添加多个请求头,两者区是前者是写在方法参数里,后者是作用在方法体

 @GET("getName")
   Call<ResponseBody> getLoginMessage5(@Header("os") String osName);

 @GET("getName")
  @Headers({"os:android","version:1.0"})
  Call<ResponseBody> getLoginMessage6(@Query("name")String username,@Query("password") String userpassword);

@Url注解则是在传参的时候,必须传入一个完整的url地址

 @POST
   Call<ResponseBody> getLoginMessage6(@Url String url);

四.Retrofit的转换器

服务器返回json字符串,转换器能自动利用转换成转成实际的javabean类。这里利用retrofit-Gson转换器
首先去该网址找到retrofit对应的gson转换器依赖版本https://github.com/square/retrofit/tree/master/retrofit-converters/gson
,将latestversion改成对应的retrofit版本

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

接着我们生成服务器返回给我们的json数据的javabean实体类
这里推荐一个网址:https://www.bejson.com/
这里可以解析我们的json数据,并且还有一个自动将json数据生成我们实体类的工具

生成后,我们将返回数据改成我们的json类:我命名我的根类为JavaBean

@POST("postName")
    @FormUrlEncoded
    Call<JavaBean> postLoginMessege(@Field("name") String username,@Field("password") String userpwd);

...调用类中:

Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("")
                                .addConverterFactory(GsonConverterFactory.create())
                                .build();
        HttpUtils httpUtils = retrofit.create(HttpUtils.class);

        Call<JavaBean> abc = httpUtils.postLoginMessege("123", "abc");
        Response<JavaBean> response = abc.execute();
        JavaBean javaBean = response.body();


通过这样就可以得到了我们的javabean对象了。

五.文件的上传和下载

1.上传文件

类似okhttp的使用方法,使用@Multipart注解和@Part注解
上传文件的时候需要一个part对象,
我们创建出我们的file文件,根据requestBody.Part转换
传入到MutipartBody.createFormBody中

	 @POST
    @Multipart
    Call<ResponseBody> upload(@Part MultipartBody.Part file);

...调用类中

Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("")
                            .build();

        HttpUtils httpUtils = retrofit.create(HttpUtils.class);
        File file = new File("1.txt");

        MultipartBody.Part part = MultipartBody.Part.createFormData("name",file.getName(), RequestBody.create(file,MediaType.parse("text/plain")));
        try {
            Response<ResponseBody> execute = httpUtils.upload(part).execute();
            
        } catch (IOException e) {
            e.printStackTrace();
        }

2.下载文件

比如我们下载一张图片,我们需要在获得response后不再是调用string,而是通过流来保存,即byteStream,接下来就用我们java io流来获取到我们的图片并且保存到本地中。注意这里我们加了个@Streaming新注解,这个是避免文件过大出现内存溢出的,以流的方式进行。

	@GET
	 @Streaming
    Call<ResponseBody> download(@Url String url);

。。。

Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("https://www.baidu.com")
                                .build();
        HttpUtils httpUtils = retrofit.create(HttpUtils.class);
        Call<ResponseBody> download = httpUtils.download("https://img.xinshuhaige.org/907/73253.jpg");
        Response<ResponseBody> response = download.execute();
        InputStream inputStream = response.body().byteStream();

        FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\a.jpg");
        int len;
        byte[] buffer = new byte[1024*4];

        while((len = inputStream.read(buffer))!=-1){

            out.write(buffer,0,len);
        }
        out.close();

六.总结

retrofit使用起来是很方便快捷的,是目前最主流的网络请求框架。但是,其配合RxJava和MVP框架来使用是更加舒服的。感兴趣的同学可以去了解一下。如果本博客对你们有用处的话,希望可以点赞加收藏,如果有什么错误的话,欢迎评论区指出!

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值