使用Retrofit 2 请求HTTP

什么是Retrofit

Retrofit是一个基于OkHttp的RESTful HTTP网络请求库,是目前比较流行的HttpClient库之一。它使得开发者可以更方便地与Web服务交互,通过简洁的API接口,实现了将REST API请求转化为Java接口调用的方式。

Retrofit的主要特点如下:

  • 简单易用:Retrofit使用简洁的注解方式定义REST API的接口,支持多种HTTP请求方法(如GET、POST、PUT、DELETE等),并自动将响应结果转换为Java对象。
  • 支持异步请求:Retrofit支持异步网络请求,可以使用RxJava、Kotlin协程等方式实现异步请求,避免在主线程中执行耗时操作。
  • 支持自定义拦截器和转换器:Retrofit可以通过自定义拦截器和转换器实现各种功能,如添加请求头、日志记录、错误处理、JSON解析等。
  • 支持文件上传和下载:Retrofit支持文件上传和下载,可以将文件作为请求体或响应体发送或接收。
  • 支持URL替换和查询参数:Retrofit支持URL替换和查询参数,可以在URL中动态替换参数,或在查询参数中传递参数。
  • 兼容多种序列化库:Retrofit支持多种序列化库,如Gson、Jackson等,可以自动将响应结果转换为Java对象。

Retrofit的使用方式

1、定义一个接口(封装URL地址和数据请求)
2、实例化Retrofit
3、通过Retrofit实例创建接口服务对象
4、接口服务对象调用接口中方法,获得Call对象
5、Call对象执行请求(异步、同步请求)

入门案例

通过GET请求访问https://www.wanandroid.com/banner/json

public interface ApiService {

    /**
     * get无参请求
     * https://www.wanandroid.com/banner/json
     */
    @GET("banner/json")
    Call<ResponseBody> getBanner();
 
}

创建Retrofit实例时需要通过Retrofit.Builder,并调用baseUrl方法设置URL

public class MainActivity {

     public static final String BASE_URL = "https://www.wanandroid.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //2.实例化Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .build();

        //3.通过Retrofit实例创建接口服务对象
        ApiService apiService = retrofit.create(ApiService.class);

        //4.接口服务对象调用接口中方法,获得Call对象
        Call<ResponseBody> call = apiService.getBanner();

        //5.Call对象执行请求(异步、同步请求)

        //同步请求:不常用,一般使用异步请求
        //Response<ResponseBody> execute = call.execute();

        //异步请求
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                //onResponse方法是运行在主线程也就是UI线程的,所以我们可以在这里直接更新ui
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        log.info("onResponse: {}", result);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                //onFailure方法是运行在主线程也就是UI线程的,所以我们可以在这里直接更新ui
                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        //call.cancel(); //取消
    }

Retrofit注解

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot与Retrofit2可以很好地结合使用,以方便地进行网络请求。下面是使用Spring Boot和Retrofit2的基本步骤: 1. 添加依赖:在项目的pom.xml文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Retrofit2 --> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.9.0</version> </dependency> <!-- Retrofit2 Gson Converter --> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>converter-gson</artifactId> <version>2.9.0</version> </dependency> </dependencies> ``` 2. 创建Retrofit实例:在Spring Boot的配置类中,使用`@Bean`注解创建一个Retrofit实例,并配置相关参数,如接口的基本URL、Gson转换器等。 ```java import okhttp3.OkHttpClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; @Configuration public class RetrofitConfig { @Bean public Retrofit retrofit() { OkHttpClient client = new OkHttpClient.Builder() // 可以添加自定义的OkHttpClient配置 .build(); return new Retrofit.Builder() .baseUrl("http://api.example.com/") // 设置接口的基本URL .client(client) .addConverterFactory(GsonConverterFactory.create()) // 设置Gson转换器 .build(); } } ``` 3. 创建API接口:定义一个接口,用于描述请求的方法和参数。 ```java import retrofit2.Call; import retrofit2.http.GET; public interface ApiService { @GET("users") Call<List<User>> getUsers(); } ``` 4. 使用Retrofit发起请求:在需要使用网络请求的地方,通过依赖注入的方式获取Retrofit实例,并调用接口方法发起请求。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import retrofit2.Call; import retrofit2.Response; import java.io.IOException; import java.util.List; @Service public class UserService { @Autowired private Retrofit retrofit; public List<User> getUsers() throws IOException { ApiService apiService = retrofit.create(ApiService.class); Call<List<User>> call = apiService.getUsers(); Response<List<User>> response = call.execute(); if (response.isSuccessful()) { return response.body(); } else { throw new IOException("请求失败:" + response.code()); } } } ``` 这样就可以在Spring Boot项目中使用Retrofit2进行网络请求了。注意要根据实际需求进行配置和调整,例如添加拦截器、设置超时时间等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程芝士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值