Retrofit使用教程(一)- Retrofit入门详解

转载请注明博客地址:http://blog.csdn.net/gdutxiaoxu/article/details/52745491

源码下载地址:https://github.com/gdutxiaoxu/RetrofitDemo.git

本人已经好久没有更新 博客了,这次更新博客打算写一下retrofit的使用教程系列的 博客,写作思路大概如下 
- 先从retrofit的基本使用讲起; 
- 接着将retrofit结合RxJava的使用; 
- 接着讲Retrofit的封装使用,(包括错误统一处理); 
- 有时间和能力的话会尝试研究一下retrofit的 源码.

本篇博客主要讲解以下问题

  • Retrofit简介
  • Retrofit的简单使用例子
  • Retrofit的get请求
  • Retrofit的put请求(提交表单数据)
  • 如何为 retrofit添加header
  • 如何提交json数据

Retrofit简介

Retrofit是square开源的网络请求库,底层是使用OKHttp封装的,网络请求速度很快.

主要有一下几种请求方法

格式 含义
@GET 表示这是一个GET请求
@POST 表示这个一个POST请求
@PUT 表示这是一个PUT请求
@DELETE 表示这是一个DELETE请求
@HEAD 表示这是一个HEAD请求
@OPTIONS 表示这是一个OPTION请求
@PATCH 表示这是一个PAT请求

各种请求注解的意思

格式 含义
@Headers 添加请求头
@Path 替换路径
@Query 替代参数值,通常是结合get请求的
@FormUrlEncoded 用表单数据提交
@Field 替换参数值,是结合post请求的

Retrofit的简单使用例子

要使用retrofit请求网络数据,大概可以分为以下几步 
- 1)添加依赖,这里以AndroidStudio为例:在build.grale添加如下依赖

 compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
 
 
  • 1
  • 2
  • 1
  • 2
  • 2) 创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
        //使用自定义的mGsonConverterFactory
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("http://apis.baidu.com/txapi/")
        .build();
mApi = retrofit.create(APi.class);

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 3)发起网络请求
mApi = retrofit.create(APi.class);
Call<News> news = mApi.getNews("1", "10");
news.enqueue(new Callback<News>() {
    @Override
    public void onResponse(Call<News> call, Response<News> response) {

    }

    @Override
    public void onFailure(Call<News> call, Throwable t) {

    }
});


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
public interface APi {

    @Headers("apikey:81bf9da930c7f9825a3c3383f1d8d766")
    @GET("word/word")
    Call<News> getNews(@Query("num") String num,@Query("page")String page);
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

到此一个简单的使用retrofit的网络请求就完成了。接下来我们来了解retrofit的各种请求方式。


Retrofit的get请求

加入我们想请求这样的网址:http://apis.baidu.com/txapi/world/world?num=10&page=1,header为”apikey:81bf9da930c7f9825a3c3383f1d8d766”,我们可以这样请求:

第一步,在interface Api中 增加如下方法


    @Headers("apikey:81bf9da930c7f9825a3c3383f1d8d766")
    @GET("word/word")
    Call<News> getNews(@Query("num") String num,@Query("page")String page);

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

第二部,在代码里面请求

//创建retrofit对象
Retrofit retrofit = new Retrofit.Builder()
        //使用自定义的mGsonConverterFactory
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("http://apis.baidu.com/txapi/")
        .build();
// 实例化我们的mApi对象
mApi = retrofit.create(APi.class); 

// 调用我们的响应的方法
Call<News> news = mApi.getNews(number, page);
news.enqueue(new Callback<News>() {
    @Override
    public void onResponse(Call<News> call, Response<News> response) {
        News body = response.body();
        Logger.i("onResponse:   ="+body.toString());
    }

    @Override
    public void onFailure(Call<News> call, Throwable t) {
        Logger.i("onResponse:   ="+t.getMessage());

    }
});


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

解释说明

假设BaseUrl是http://apis.baidu.com/txapi/的前提下

  • 1)其中 @GET(“word/word”)会追加到baseUrl :http://apis.baidu.com/txapi/的后面,即变成:http://apis.baidu.com/txapi/world/world
  • 2)@Query(“num”) String num,@Query(“page”)String page;分别对应键值的名称与值。会追加到http://apis.baidu.com/txapi/world/world的后面,请求网址即变成:http://apis.baidu.com/txapi/world/world?num=10&page=1
  • 3) @Headers(“apikey:81bf9da930c7f9825a3c3383f1d8d766”)是 在基础之上为 其添加响应头
  • 4)如果想继续增加参数,只需要在方法参数追加这样的形式就OK了: 
    ,@Query(“page”)String page

    @Headers("apikey:81bf9da930c7f9825a3c3383f1d8d766")
    @GET("word/word")
    Call<News> getNews(@Query("num") String num,@Query("page")String page,@Query("type") String type);
       
       
    • 1
    • 2
    • 3
    • 1
    • 2
    • 3
  • 5)加入我们想要请求这样的网址http://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1,,我们可以这样写

     @Headers({"apikey:81bf9da930c7f9825a3c3383f1d8d766" ,"Content-Type:application/json"})
    @GET("{type}/{type}")
    Call<News> tiYu(@Path("type") String type, @Query("num") String num,@Query("page")String page);
    String type="tiyu";
    Call<News> news = api.tiYu(type,number, page);
       
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 1
    • 2
    • 3
    • 4
    • 5

retrofit的post请求

假如我们想要 请求这样的网址http://apis.baidu.com/txapi/world/world?以post的 方式提交这样的 数据:num=10&page=1,我们可以写成 如下的 样子,注意post的时候必须使用@Field这种形式的注解,而不是使用@Query这种形式的注解,其他的 与get请求一样,这样只给出核心代码

@FormUrlEncoded
@Headers({"apikey:81bf9da930c7f9825a3c3383f1d8d766" ,"Content-Type:application/json"})
@POST("world/world")
Call<News> postNews(@Field("num") String num, @Field("page")String page);


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

如何为retrofit添加请求头head

总共有以下几种方式

第一种方法

在OKHttpClient interceptors里面进行处理,这样添加的headKey不会覆盖掉 前面的 headKey

okHttpClient.interceptors().add(new Interceptor() {  
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("header-key", "value1")
                    .addHeader("header-key", "value2");

        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

第二种方法

同样在在OKHttpClient interceptors里面进行处理,这样添加的headKey会覆盖掉 前面的 headKey

okHttpClient.interceptors().add(new Interceptor() {  
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .header("headerkey", "header-value"); // <-- this is the important line

        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

第三种方法

利用 retrofit自带的注解,比如我们想要添加这样的请求头:”apikey:81bf9da930c7f9825a3c3383f1d8d766” ,”Content-Type:application/json”;则可以写成如下的 样式

@Headers({"apikey:81bf9da930c7f9825a3c3383f1d8d766" ,"Content-Type:application/json"})
@GET("world/world")
Call<News> getNews(@Query("num") String num,@Query("page")String page);


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

通过post提交json数据

Post 提交JSON数据

有时提交的数据量比较大时,用键值对的方式提交参数不太方便,Retrofit可以通过@Body注释,直接传递一个对象给请求主体,Retrofit通过JSON转化器,把对象映射成JSON数据。

假设我们需要提交的数据为

{
    "id": 1,
    "text": "my task title"
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
  • 接口定义:

    public interface TaskService {  
    @Headers({"Content-Type: application/json","Accept:  application/json"})
    @POST("/tasks")
    Call<Task> createTask(@Body Task task);
    }
       
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 1
    • 2
    • 3
    • 4
    • 5
  • 传递实体需要有Model:

    public class Task {  
    private long id;
    private String text;
    
    public Task() {}
    public Task(long id, String text) {
        this.id = id;
        this.text = text;
    }
    }
       
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  • 客户端调用:

    Task task = new Task(1, "my task title");  
    Call<Task> call = taskService.createTask(task);  
    call.enqueue(new Callback<Task>() {}); 
       
       
    • 1
    • 2
    • 3
    • 1
    • 2
    • 3
  • 这样,服务端得到的是JOSN数据:

    {
    "id": 1,
    "text": "my task title"
    }
       
       
    • 1
    • 2
    • 3
    • 4
    • 1
    • 2
    • 3
    • 4

到此,这篇博客为止

题外话:

其实retrofit在5月份实习的时候就接触了,之前为什么不写 博客了,因为网上的 使用教程很多,觉得没有必要。到后面学习的时候,发现retrofit的使用时 比较灵活的,并且使用方法也是相对较多的,于是,就写了retrofit这系列的使用博客。

转载请注明博客地址:http://blog.csdn.net/gdutxiaoxu/article/details/52745491

源码下载地址:https://github.com/gdutxiaoxu/RetrofitDemo.git

参考官网地址http://square.github.io/retrofit/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
retrofit-spring-boot-starter是一个用于整合Retrofit库和Spring Boot的starter项目,它可以简化在Spring Boot中使用Retrofit的配置和使用。 以下是retrofit-spring-boot-starter的使用方法: 1. 在你的Spring Boot项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.github.lianjiatech</groupId> <artifactId>retrofit-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> ``` 2. 创建一个接口,用于定义Retrofit的API接口。例如: ```java import retrofit2.http.GET; import retrofit2.http.Path; public interface MyApi { @GET("/users/{username}") User getUser(@Path("username") String username); } ``` 3. 在你的Spring Boot应用程序中,使用`@Autowired`注解将Retrofit的API接口注入到你的代码中。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import retrofit2.Retrofit; @Service public class MyService { private final MyApi myApi; @Autowired public MyService(Retrofit retrofit) { this.myApi = retrofit.create(MyApi.class); } public User getUser(String username) { return myApi.getUser(username); } } ``` 4. 现在你可以在你的代码中使用`MyService`来调用Retrofit的API接口了。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { private final MyService myService; @Autowired public MyController(MyService myService) { this.myService = myService; } @GetMapping("/users/{username}") public User getUser(@PathVariable String username) { return myService.getUser(username); } } ``` 以上是retrofit-spring-boot-starter的基本用法。你可以根据自己的需求进行配置和使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值