前言

Retrofit会将你的HTTP接口调用转换为java的interface,你不必去实现这个接口,交给Retrofit来创建动态代理.

首先,贴上官网Javadoc.

官网上的例子

加依赖,下jar包什么的就跳过了,来一个官网例子就知道怎么用了.

//interface
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
//创建工厂
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build(); //创建代理对象
GitHubService service = retrofit.create(GitHubService.class);
//调用方法获得Call对象
Call<List<Repo>> repos = service.listRepos("octocat");

此时还没有发送请求去调用HTTP API.Call对象提供了同步和异步两种方式来发送请求:

//同步,出错时抛出IO或者Runtime异常
Response response = call.execute();
//异步
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response)
{
//TODO 成功时的回调
} @Override
public void onFailure(Call call, Throwable t) {
//TODO 失败时的回调
}
});

关于Reponse和Call的细节,可以去看Javadoc.

注解介绍

Retrofit的类还是挺少的,这里就介绍些我用过的注解吧.

请求方式的注解

@GET,@POST,@DELETE,@HEAD,@PUT,@PATCH@HTTP.除了@HTTP之外都没什么好说的.

@HTTP有三个参数:method,hasBody和path:

@HTTP(method = "DELETE", path = "admin/delete_user", hasBody = true)
Call<Message> deleteUser(@Body UserVO vo, @Header("Apitoken") ApiToken apiToken
, @Header("X-Forwarded-For") String forwardedFor);

一些蛋疼的DELETE,POST或者PUT API的response会有body,但是@DELETE,@POST,@PUT都不能有body,这时候就要用@HTTP了.

参数位置的注解

@Header,@Body,@Path,@Query,@QueryMap,'@Headers'

对应的参数如果不是基本类型包装类的话会自动转换为json,没有记错的话,@Query,@QueryMap不能和'@POST','@PUT'搭配使用,直接来点例子吧.

@GET("strategy")
Call<List<Strategy>> getStrategyList(@Query("tid") Long tid,
@Header("Apitoken")ApiToken apiToken,
@Header("X-Forwarded-For") String forwardedFor);
@GET("graph/endpoint_counter")
Call<List<String>> getCounterOfEndpoint(@QueryMap Map<String, String> map,
@Header("Apitoken") ApiToken apiToken,
@Header("X-Forwarded-For") String forwardedFor);
//不要在意这个奇怪的API
@Headers({"Content-type: application/x-www-form-urlencoded"})
@GET("alarm/eventcases")
Call<List<EventCase>> getEventCasesById(@Query("eventid") String eventId, @Header("Apitoken") ApiToken apiToken,
@Header("X-Forwarded-For") String forwardedFor);

请求数据格式的注解

需要注意的是格式和参数的注解是对应的.

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

转换器

通过添加不同的依赖来使用不同的转换器:

  • 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

使用Retrofit2调用HTTP API的更多相关文章

  1. ReactiveX 学习笔记(14)使用 RxJava2 + Retrofit2 调用 REST API

    JSON : Placeholder JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站. ...

  2. Unity在Android和iOS中如何调用Native API

    本文主要是对unity中如何在Android和iOS中调用Native API进行介绍. 首先unity支持在C#中调用C++ dll,这样可以在Android和iOS中提供C++接口在unity中调 ...

  3. C#调用windows API的一些方法

    使用C#调用windows API(从其它地方总结来的,以备查询) C#调用windows API也可以叫做C#如何直接调用非托管代码,通常有2种方法: 1.  直接调用从 DLL 导出的函数. 2. ...

  4. 使用Python调用Flickr API抓取图片数据

    Flickr是雅虎旗下的图片分享网站,上面有全世界网友分享的大量精彩图片,被认为是专业的图片网站.其API也很友好,可以实现多种功能.这里我使用了Python调用其API获得了大量的照片数据.需要注意 ...

  5. WebApi系列~通过HttpClient来调用Web Api接口

    回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...

  6. C#调用Windows API函数截图

    界面如下: 下面放了一个PictureBox 首先是声明函数: //这里是调用 Windows API函数来进行截图 //首先导入库文件 [System.Runtime.InteropServices ...

  7. 以短链服务为例,探讨免AppKey、免认证、Ajax跨域调用新浪微博API

    新浪微博的API官方提供了很多种调用方式,支持编程的,归根结底就是两种: 1.基于Oauth协议,使用Open API.(http://open.weibo.com/wiki/%E6%8E%88%E6 ...

  8. 【转】用C#调用Windows API向指定窗口发送

    一.调用Windows API. C#下调用Windows API方法如下: 1.引入命名空间:using System.Runtime.InteropServices; 2.引用需要使用的方法,格式 ...

  9. MSIL 教程(二):数组、分支、循环、使用不安全代码和如何调用Win32 API(转)

    转自:http://www.cnblogs.com/Yahong111/archive/2007/08/16/857574.html 续上文[翻译]MSIL 教程(一) ,本文继续讲解数组.分支.循环 ...

随机推荐

  1. 经典Dialog插件Layer

    Github上只有一个test,所以最好还是到官网去学习,官网的示例写的很详尽,难得一见的设计思路和灵活性都极好的插件.下面是我自己test过的demo <!DOCTYPE html> & ...

  2. 从零搭建SSM框架(一)搭建工程

    工程结构 一.cnki-parent 1.新建maven project  2.pom.xml <project xmlns="http://maven.apache.org/POM/ ...

  3. python核心编程笔记——Chapter2

    对于.py文件,任何一个空的式子都不会有什么输出,如下: #!/usr/bin/env python #-*-coding=utf-8-*- #无任何效果,空语句 1 + 2 * 4 对于i++,++ ...

  4. mac nginx 安装及PHP配置

    安装nginx 1.安装brew命令 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/mas ...

  5. POJ 2230 Watchcow && USACO Watchcow 2005 January Silver (欧拉回路)

    Description Bessie's been appointed the new watch-cow for the farm. Every night, it's her job to wal ...

  6. CF448C Painting Fence

    传送门 Descriptionzed 最近总是受到 Farmer 的困扰,因此他在自家的门前插了一排栅栏以防农气的入侵.栅栏由 N 个竖条栅栏横向组成,每个竖条栅栏宽度为 1.过了一段时间,zed 觉 ...

  7. Python数据类型(整型,字符串类型,列表)

    一:数据的概念 1.数据是什么 x=10,数据10就是我们要存储的数据. 2.为什么数据要分不同的种类? 因为数据是用来表示状态的,不同的状态就要用不同类型的数据去表示. 3:Python中常见的数据 ...

  8. CentOS7.3下的一个iptables配置

    centos7.3默认使用的防火墙应该是firewall,而不是iptables.而我们xxmj服务器使用的是iptables防火墙.所以,在配置防火墙之前,我们需要先关闭firewall,安装ipt ...

  9. orcale数据库分配用户

    account lock:创建用户的时候锁定用户 account unlock:创建用户的时候解锁用户,默认该选项 create user zhou8–用户名 identified by zhou88 ...

  10. Scrapy项目之User timeout caused connection failure(异常记录)

    Windows 10家庭中文版,Python 3.6.4,Scrapy 1.5.0, 提示:此文存在问题,真正测试, 请勿阅读, 07-14 14:26更新: 经过两个多小时的测试,发现此问题的原因是 ...