Android retrofit

news/2025/2/12 18:51:28/

目录

一.简介

二.基本使用

三.注解

四.转换器

五.适配器

六.文件上传与下载


一.简介
A type-safe HTTP client for Android and Java。封装了OkHttp,也是由Square公司贡献的一个处理网络请求的开源项目。
square/retrofit: A type-safe HTTP client for Android and the JVM (github.com)
在bulid.gradle中添加依赖
implementation 'com.squareup.retrofit2:retrofit:2.11.0'
二.基本使用

服务器域名: https:/ /www.httpbin.org/

接口:post
参数:username,password
接口:get 
参数:usernamespassword

1.根据Http接口创建Java接口
public interface HttpbinService {@POST("post")@FormUrlEncodedCall<ResponseBody> post(@Field("username") String userName,@Field("password") String pwd);@GET("get")Call<ResponseBody> get(@Query("username") String userName,@Query("password") String pwd);
}

2.创建Retrofit对象,并生成接口实现类对象

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://httpbin.org/").build();
HttpbinService httpbinService = retrofit.create(HttpbinService.class);

3.接口实现类对象调用对应方法获得响应

retrofit2.Call<ResponseBody> call = httpbinService.post("xx", "123");call.enqueue(new retrofit2.Callback<ResponseBody>() {@Overridepublic void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {try {Log.i("TAG",response.body().string());} catch (IOException e) {e.printStackTrace();}}@Overridepublic void onFailure(retrofit2.Call<ResponseBody> call, Throwable throwable) {}});
三.注解
方法注解:@GET,@POST,@PUT,@DELETE,@PATH,@HEAD,@OPTIONS,@HTTP
标记注解:@FormUrlEncoded,@Multipart,@Streaming
参数注解:@Query,@QueryMap,@Body,@Field,@FieldMap,@Part,@PartMap
其他注解:@Path,@Header, @Headers,@Url
详细使用请参考 GET (retrofit API) (square.github.io)
public interface HttpbinService {@POST("post")@FormUrlEncodedCall<ResponseBody> post(@Field("username") String userName,@Field("password") String pwd);@GET("get")Call<ResponseBody> get(@Query("username") String userName,@Query("password") String pwd);@HTTP(method = "POST",path = "post",hasBody = true)Call<ResponseBody> http(@Field("username") String userName,@Field("password") String pwd);@POST("post")Call<ResponseBody> postBody(@Body RequestBody body);@POST("{id}") //("/xxx/{pageNum}")@FormUrlEncodedCall<ResponseBody> postInPath(@Path("id") String path,@Header("os") String os1,@Field("username") String userName,@Field("password") String pwd);//@Path("pageNum")@Headers({"os:android","version:1.0"})@POST("post")Call<ResponseBody> postWithHeader();@POST()Call<ResponseBody> postUrl(@Url String url);
}

四.转换器
在我们接到服务器的响应后,目前无论是OkHttp还是Retrofit都只能接收到String字符串类型的数据,在实际开发中,经常需要对字符串进行解析将其转变为一个Java Bean对象。比如服务器响应数据为JSON格式字符串,那么可以自己利用GSON库完成反序列化的操作。而Retrofit提供了多个转换器使得响应能够完成自动的数据转换。以json解析为例:
添加依赖
implementation 'com.squareup.retrofit2:converter-gson:2.11.0'

手动转换

public interface WanAndroidService {@POST("user/login")@FormUrlEncodedCall<ResponseBody> login(@Field("username") String username,@Field("password") String pwd);
}
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.wanandroid.com/").build();WanAndroidService wanAndroidService = retrofit.create(WanAndroidService.class);@Testpublic void loginTest() throws IOException {Call<ResponseBody> call = wanAndroidService.login("xxx","123456");Response<ResponseBody> response  =call.execute();String result  = response.body().string();System.out.println(result);//手动进行数据转换BaseResponse baseResponse  = new Gson().fromJson(result,BaseResponse.class);System.out.println(baseResponse);}

自动转换

修改接口方法:
@POST("post")
@FormUrlEncoded
Call<JavaBean> post(@Field("username") String userName, @Field("password") String pwd);
public interface WanAndroidService2 {@POST("user/login")@FormUrlEncodedCall<BaseResponse> login(@Field("username") String username, @Field("password") String pwd);
}
Retrofit retrofit1 = new Retrofit.Builder().baseUrl("https://www.wanandroid.com/").addConverterFactory(GsonConverterFactory.create())  //添加转换器.build();WanAndroidService2 wanAndroidService2 = retrofit1.create(WanAndroidService2.class);@Testpublic void loginConvertTest() throws IOException {Call<BaseResponse> call = wanAndroidService2.login("xxx","123456");Response<BaseResponse> response = call.execute();BaseResponse baseResponse = response.body();System.out.println(baseResponse);}
五.适配器
在实际开发中,可能会存在:需要先请求A接口,再请求B接口的情况。比如需要请求获取收藏文章列表,但是需要先登录拿到Cookie才能请求收藏文章列表接口。此时请求就有了先后顺序,为了完成这个功能,需要不断回调。Retrofit的接口方法返回类型必须是Call,如果能够将Call改为RxJava中的Observable,对于嵌套的情况,就能得到非常方便优雅的解决。这就是适配器的功能,如果我们想要返回的不是Call,适配器就能够帮助我们转换为其他类型。以RxJava3为例:
添加依赖
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.11.0'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.2'
修改接口方法:
@POST("post")
@FormUrlEncoded
Observable<JavaBean> post(@Field("username") String userName, @Field("password") String pwd);
@POST("user/login")@FormUrlEncodedFlowable<BaseResponse> login2(@Field("username") String username, @Field("password") String pwd);@GET("lg/collect/list/{pageNum}/json")Flowable<ResponseBody> getArticle(@Path("pageNum") int pageNum);
Map<String, List<Cookie>> cookies = new HashMap<>();Retrofit retrofit2 = new Retrofit.Builder().baseUrl("https://www.wanandroid.com/").callFactory(new OkHttpClient.Builder().cookieJar(new CookieJar() {@Overridepublic void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {cookies.put(httpUrl.host(), list);}@Overridepublic List<Cookie> loadForRequest(HttpUrl url) {List<Cookie> cookies = WanAndroidUnitTest.this.cookies.get(url.host());return cookies == null ? new ArrayList<>() : cookies;}}).build()).addConverterFactory(GsonConverterFactory.create())  //添加转换器.addCallAdapterFactory(RxJava3CallAdapterFactory.create())  //添加适配器.build();WanAndroidService2 wanAndroidService3 = retrofit2.create(WanAndroidService2.class);@Testpublic void rxjavaTest() {wanAndroidService3.login2("xxxx","123456").flatMap(new Function<BaseResponse, Publisher<ResponseBody>>() {@Overridepublic Publisher<ResponseBody> apply(BaseResponse baseResponse) throws Throwable {return wanAndroidService3.getArticle(0);}}).observeOn(Schedulers.io()).subscribeOn(Schedulers.newThread())   //AndroidSchedulers.mainThread().subscribe(new Consumer<ResponseBody>() {@Overridepublic void accept(ResponseBody responseBody) throws Throwable {System.out.println(responseBody.string());}});while (true){}}
六.文件上传与下载
@POST("post")@MultipartCall<ResponseBody> upload(@Part MultipartBody.Part file);@GETCall<ResponseBody> download(@Url String url);
@Testpublic void uploadFileTest() throws IOException {File file = new File("H:\\Users\\ASUS\\Desktop\\f1.txt");MultipartBody.Part part = MultipartBody.Part.createFormData("file1", "f1.txt",RequestBody.create(MediaType.parse("text/plain"), file));Call<ResponseBody> call = uploadService.upload(part);System.out.println(call.execute().body().string());}@Testpublic void downloadFileTest() throws IOException {Response<ResponseBody> response = uploadService.download("https://xxx.apk").execute();InputStream inputStream = response.body().byteStream();FileOutputStream fos = new FileOutputStream("H:\\Users\\ASUS\\Desktop\\1.apk");int len;byte[] buffer = new byte[4096];while ((len = inputStream.read(buffer)) != -1){fos.write(buffer,0,len);}fos.close();inputStream.close();}

相关参考

Retrofit (square.github.io)​​​​​​​

ReactiveX/RxJava: RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM. (github.com)

ReactiveX/RxAndroid: RxJava bindings for Android (github.com)​​​​​​​


http://www.ppmy.cn/news/1420970.html

相关文章

Qt创建基于应用程序的插件

应用程序插件 什么是插件插件的好处插件的种类应用程序插件创建应用程序的插件步骤:创建测试插件的应用程序步骤:应用程序插件示例开发环境创建示例生成插件运行结果总结什么是插件 插件是一种用于应用程序功能扩展和增强,且按照特定规范编写的应用程序接口的程序。 插件的…

Composer安装与配置详解

目录 第一章:Composer简介 1.1 什么是Composer? 1.2 Composer与传统的依赖管理工具的区别 1.3 Composer的发展历程 1.4 本章小结 第二章:Composer安装 2.1 全局安装与项目内安装 2.1.1 全局安装 安装步骤 2.1.2 项目内安装 安装步骤 2.2 不同操作系统下的安装方…

js自定义丝滑滚动

最近做官网&#xff0c;实现一个分屏滚动效果&#xff0c;考虑到滚动结束后还要自定义&#xff0c;每屏的触发动画效果&#xff0c;又要满足响应式&#xff0c;所以只能自己写一个滚动方法&#xff1b; 核心方法 /*params targetY:500, 目标距离 Number params duration: 1000…

php:实现压缩文件上传、解压、文件更名、压缩包删除功能

效果图 1.上传文件 2.压缩包文件 3.itemno1文件 4.上传到系统路径\ItemNo 5.更名后的itemno1文件(命名&#xff1a;当天日期六位随机数) 代码 <form action"<?php echo htmlspecialchars($_SERVER[PHP_SELF], ENT_QUOTES, UTF-8); ?>" method"post…

C#:循环中断

任务描述 实现九九乘法表&#xff0c;按照编程要求&#xff0c;使用break跳出循环 测试说明 测试过程&#xff1a; 平台将编译用户补全代码&#xff0c;并根据程序的输出判断程序是否正确。 以下是测试样例&#xff1a; 测试输入&#xff1a; 预期输出&#xff1a; we found…

打一把王者的时间,学会web页面测试方法与测试用例编写

一、输入框 1、字符型输入框&#xff1a; &#xff08;1&#xff09;字符型输入框&#xff1a;英文全角、英文半角、数字、空或者空格、特殊字符“~&#xff01;#&#xffe5;%……&*&#xff1f;[]{}”特别要注意单引号和&符号。禁止直接输入特殊字符时&#xff0c;…

Redis系列之基于Linux单机安装

Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库&#xff0c;并提供多种语言的 API。最近学习需要用到Redis&#xff0c;所以就去Linux服务器上部署一个&#xff0c;做下记录&#xff0c;方便…

MoonBit 2024 Qcon 北京精彩回顾速览

2024年4月11日至13日&#xff0c;QCon 全球软件开发大会暨智能软件开发生态展在北京国测国际会议会展中心举办。本次 QCon 大会汇集了100技术大咖&#xff0c;通过1场主论坛、近30分论坛以及5场高端闭门交流和多场闪电演讲等多样化的活动形式&#xff0c;促进了与会者的深入交流…