Retrofit——01.入门

mac2025-10-16  7

Retrofit 是一个 Restful API 的 HTTP 网络请求框架的封装,网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装

注:Restful API了解请移步 RESTful API是什么?

使用步骤

添加Retrofit库的依赖: implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

第一个是Retrofit依赖,后面是gson转换需要用到

创建用于描述网络请求 的接口 public interface ApiInterface { @FormUrlEncoded @POST("/lookup/findDictVersion.wx") Observable<ResultBean> getVersion(@Field("customerId") String customerId); } 发送请求 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://xxxx.aaaa.cn") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); ApiInterface apiInterface = retrofit.create(ApiInterface.class); apiInterface.getVersion("") .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Observer<ResultBean>() { @Override public void onSubscribe(Disposable d) { Log.e("log","onSubscribe"); } @Override public void onNext(ResultBean value) { Log.e("log",value.data.downUrl); } @Override public void onError(Throwable e) { Log.e("log","onError"); } @Override public void onComplete() { Log.e("log","onComplete"); } });

注解 网络请求方式 标记

@FormUrlEncoded 表示发送form-encoded的数据,每个键值对需要用@Filed来注解键名,随后的对象需要提供值。@Multipart 表示发送form-encoded的数据(适用于有文件上传的场景),每个键值对需要用@Part来注解键名,随后的对象需要提供值。 public interface GetRequest_Interface { /** *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded) * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age); /** * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型 * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息), */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file); }

网络请求参数

@Header & @Headers 添加请求头 &添加不固定的请求头 // @Header @GET("user") Call<User> getUser(@Header("Authorization") String authorization) // @Headers @Headers("Authorization: authorization") @GET("user") Call<User> getUser() // 以上的效果是一致的。 // 区别在于使用场景和使用方式 // 1. 使用场景:@Header用于添加不固定的请求头,@Headers用于添加固定的请求头 // 2. 使用方式:@Header作用于方法的参数;@Headers作用于方法 @Body 以 Post方式 传递 自定义数据类型 给服务器,如果提交的是一个Map,那么作用相当于 @Field,不过Map要经过 FormBody.Builder 类处理成为符合 Okhttp 格式的表单,如: FormBody.Builder builder = new FormBody.Builder(); builder.add("key","value"); @Field & @FieldMap 发送 Post请求 时提交请求的表单字段,与 @FormUrlEncoded 注解配合使用 public interface GetRequest_Interface { /** *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded) * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age); /** * Map的key作为表单的键 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map); } @Part & @PartMap 发送 Post请求 时提交请求的表单字段,与@Field的区别:功能相同,但携带的参数类型更加丰富,包括数据流,所以适用于 有文件上传 的场景,与 @Multipart 注解配合使用 public interface GetRequest_Interface { /** * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型 * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息), */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file); /** * PartMap 注解支持一个Map作为参数,支持 {@link RequestBody } 类型, * 如果有其它的类型,会被{@link retrofit2.Converter}转换,如后面会介绍的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter} * 所以{@link MultipartBody.Part} 就不适用了,所以文件只能用<b> @Part MultipartBody.Part </b> */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file); @POST("/form") @Multipart Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args); } @Query和@QueryMap 用于 @GET 方法的查询参数(Query = Url 中 ‘?’ 后面的 key-value) 如:url = http://www.println.net/?cate=android,其中,Query = cate 配置时只需要在接口方法中增加一个参数即可: @GET("/") Call<String> cate(@Query("cate") String cate); @Path URL地址的缺省值 public interface GetRequest_Interface { @GET("users/{user}/repos") Call<ResponseBody> getBlog(@Path("user") String user ); // 访问的API是:https://api.github.com/users/{user}/repos // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用) } @Url 直接传入一个请求的 URL变量 用于URL设置 public interface GetRequest_Interface { @GET Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll); // 当有URL注解时,@GET传入的URL就可以省略 // 当GET、POST...HTTP等方法中没有设置Url时,则必须使用 {@link Url}提供 }
最新回复(0)