retrofit2学习笔记

来源:互联网 发布:java maven ant 编辑:程序博客网 时间:2024/05/28 16:07

简介

Every method must have an HTTP annotationthat provides the request method and relative URL. There are five built-inannotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resourceis specified in the annotation.

特点:

Retrofit使用注解来描述HTTP请求:
1.URL参数的替换和query参数的支持
2.对象转化为请求体(如:JSON,protocol buffers等)
3.多重请求体和文件上传

 

使用条件:最小支持jdk7及android2.3以上版本

使用配置

Android studio下配置gradle(直接去例子中抄)

compile'com.squareup.retrofit2:retrofit:(insert latest version)'

例:compile'com.squareup.retrofit2:retrofit:2.1.0'

配置MAVEN

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>(insert latest version)</version>
</dependency>

如果项目需要混淆,则需要在混淆文件中加入一下代码

# Platform calls Class.forName on typeswhich do not exist on Android to determine platform.

-dontnote retrofit2.Platform

# Platform used when running on RoboVM oniOS. Will not be used at runtime.

-dontnoteretrofit2.Platform$IOS$MainThreadExecutor

# Platform used when running on Java 8 VMs.Will not be used at runtime.

-dontwarn retrofit2.Platform$Java8

# Retain generic type information for useby reflection by converters and adapters.

-keepattributes Signature

# Retain declared checked exceptions foruse by a Proxy instance.

-keepattributes Exceptions

基本说明

请求说明


每一个请求方法必须要有一个HTTP注解来指明明请求的方式和相对URL。有五种内置(支持)的注解请求方式:GET、POST、PUT、DELETE以及HEAD。资源的相对URL需要在注解里面明确给出。

除此之外,你还可以在相对url中拼接请求参数

url指定

一个请求的URL可以通过替换块和请求方法的参数来进行动态的更新。替换块是由被{}包裹起来的数字或字母组成的字符串构成的,相应的方法参数需要由@Path来注解同样的字符串。

请求参数也能添加

复杂的url可以用map集合去构建


通过@Body 注解可以把一个对象作为请求的主体。

The object will also be converted using aconverter specified on the Retrofit instance. If no converter isadded, onlyRequestBody can be used.

另外,这个对象将会被指定的一个转化器实例转换。如果没有添加转换器,那么就只有请求体式有用的。(翻译的不是很准确)


@Header注解的参数必须提供,如果为null,则则头将被省略。

 

调用实例可以执行同步请求或异步请求。每个实例只能使用一次,但叫clone()方法将创建一个新的实例,可以继续使用。

在Android中,回调将在主线程中执行。在JVM中,回调将在执行HTTP请求同一个线程中发生。


Retrofit默认会提供一些默认值,但是,也允许自定义。

 

 

使用

注解说明:

@GET说明,就表示get请求

@POST POST网络请求

@Query("tag") String tag说明,单个请求参数,拼接后是tag=tag,会拼接在url后面

@Path说明,路径参数,替换url中的“{”和“}”括起来的内容

@field说明,指定表单域中每个控件的name及相应数值

@FormUrlEncoded说明,堆内容做编码处理,避免乱码

@FieldMap表单域集合

@Body post提交分块请求

@Multipartpost提交分块请求,如果上传文件,必须指定Multipart

@NonNull

@Headers头信息参数

@QueryMap Map<String,String> map说明,参数比较多时,用map构建的参数集合

使用步骤:

1、导包

2、创建接口

3、创建retrofit实例

4、创建接口实例

5、返回call对象,执行同步或异步请求。

0 0