Retrofit使用介绍

常用网络请求框架

在这里插入图片描述

Android-async-http

HttpClient不推荐使用、6.0已删除,转用HttpURLConnection
DefaultHttpClient和它的兄弟AndroidHttpClient都是HttpClient具体的实现类,它们都拥有众多的API,而且实现比较稳定,bug数量也很少。但同时也由于HttpClient的API数量过多,使得我们很难在不破坏兼容性的情况下对它进行升级和扩展。虽然高效稳定,但是维护成本高昂,故android 开发团队不愿意在维护该库而是转投更为轻便的 HttpUrlConnection。
HttpURLConnection 是一种多用途、轻量极的 HTTP 客户端, HttpURLConnection 的 API 提供的比较简单,可以更加容易地去使用和扩展它。

Volley

Volley的request和response把数据放到byte数组里,不支持输入输出流,如果大文件多了,数据就非常大且多,消耗内存,不如直接返回Stream那样具备可操作性

OkHttp

Android4.4源码中,HttpURLConnection底层已经替换成了OkHttp实现
基于NIO和Okio(IO:阻塞式,NIO:非阻塞式, Okio是Square公司基于IO和NIO基础上做的一个更简单、高效处理数据流的库)

Retrofit

通过注解方式配置网络请求参数
支持高性能网络请求(OkHttp)
简单易用(高度封装和注解)
支持多种数据解析器(Convert)和网络请求适配器(CallAdapter)

Retrofit Introduction

Type-safe HTTP client for Android and Java by Square, Inc.
Retrofit 是Square开发的一个 基于OkHttp的网络请求框架(的封装)

高度封装,简洁易用、高度解耦,职责细分(基于注解、支持多种Convert和CallAdapter)
在这里插入图片描述
Retrofit 仅负责 网络请求接口的封装,网络请求的工作本质上是 OkHttp 完成
github:https://github.com/square/retrofit
retrofit:https://square.github.io/retrofit/

Retrofit基本使用

在这里插入图片描述

Retrofit注解

REQUEST METHOD

支持5种内置注解网络请求方法
GETPOST, PUT, DELETE, and HEAD.

网络请求标记

网络请求参数

支持多种请求参数注解
@Headers、@Header、@Body、@Field、@FieldMap、@Part
@PartMap、@Query、@QueryMap、@Path、@URL

GET的使用

@GET("users/list")
@GET("users/list?sort=desc")

@Query的使用

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

For complex query parameter combinations a Map can be used.(复杂参数构建使用

@QueryMap的使用

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

@Body的使用

An object can be specified for use as an HTTP request body with the @Body annotation.

@POST("users/new")
Call<User> createUser(@Body User user);

The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBodycan be used.

@FormUrlEncoded、@Field的使用

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

@Multipart、@Part的使用

@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);




//先创建 service
FileUploadService service = retrofit.create(FileUploadService.class);

//构建要上传的文件
File file = new File(filename);
RequestBody requestFile =
        RequestBody.create(MediaType.parse("application/otcet-stream"), file);

MultipartBody.Part body =
        MultipartBody.Part.createFormData("aFile", file.getName(), requestFile);

String descriptionString = "This is a description";
RequestBody description =
        RequestBody.create(
                MediaType.parse("multipart/form-data"), descriptionString);

Call<ResponseBody> call = service.upload(description, body);

Multipart parts use one of Retrofit’s converters or they can implement RequestBody to handle their own serialization.

@Headers的使用

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();

@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);

You can set static headers for a method using the @Headers annotation.
Note that headers do not overwrite each other. All headers with the same name will be included in the request.

@Header的使用

A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)

@HeaderMap的使用

Similar to query parameters, for complex header combinations, a Map can be used.

@GET("user")
Call<User> getUser(@HeaderMap Map<String, String> headers)

网络请求参数注解汇总

网络请求标记

在这里插入图片描述

网络请求参数标记

在这里插入图片描述

Convert

By default, Retrofit can only deserialize HTTP bodies into OkHttp’s ResponseBody type and it can only accept its RequestBody type for @Body.

  • Gson: com.squareup.retrofit2:converter-gson
  • Jackson: com.squareup.retrofit2:converter-jackson
  • Moshi: com.squareup.retrofit2:converter-moshi
  • Protobuf: com.squareup.retrofit2:converter-protobuf
  • Wire: com.squareup.retrofit2:converter-wire
  • Simple XML: com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
  • 自定义Convert:extends Convert.Factory

example

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();
GitHubService service = retrofit.create(GitHubService.class);

CUSTOM CONVERTERS

extends the Converter.Factory
  static class FileRequestBodyConverterFactory extends Converter.Factory {
    @Override
    public Converter<File, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
      return new FileRequestBodyConverter();
    }
  }

  static class FileRequestBodyConverter implements Converter<File, RequestBody> {

    @Override
    public RequestBody convert(File file) throws IOException {
      return RequestBody.create(MediaType.parse("application/otcet-stream"), file);
    }
  }

CallAdapter

  • AndroidCallAdapter(默认)
  • guava com.squareup.retrofit2:adapter-guava:2.0.2
  • Java8 com.squareup.retrofit2:adapter-java8:2.0.2
  • rxjava com.squareup.retrofit2:adapter-rxjava:2.0.2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值