Retrofit-基本使用

本文介绍如何使用Retrofit库进行HTTP请求操作,并通过一个具体的天气查询案例演示其使用流程,包括定义POJO类、请求接口及实现Retrofit调用。

前言
Retrofit 是 Square 公司出品的 HTTP 请求库;官方的介绍:A type-safe HTTP client for Android and Java。
Retrofit是一套RESTful架构的Android(Java)客户端实现,基于注解,提供JSON to POJO(Plain Ordinary Java Object,简单Java对象),POJO to JSON,网络请求(POST,GET,PUT,DELETE等)封装。

基本使用
Github链接:
https://github.com/square/retrofit
引入依赖
compile ‘com.squareup.retrofit2:retrofit:2.0.2’

下面的实例是获取城市的天气,以北京为例,url地址为:http://www.weather.com.cn/data/sk/101010100.html

1、定义POJO或模型实体类
从服务器获取的JSON数据将被填充到这种类的实例中。

public class WeatherinfoResult {
    private Weatherinfo weatherinfo;

    public Weatherinfo getWeatherinfo() {
        return weatherinfo;
    }

    public void setWeatherinfo(Weatherinfo weatherinfo) {
        this.weatherinfo = weatherinfo;
    }
}
//
public class Weatherinfo {
    private String city;
    private String cityid;
    private String temp;
    private String WD;
    private String WS;
    private String SD;
    private String WSE;
    private String time;
    private String isRadar;
    private String Radar;
    private String qy;
    private String rain;
    //省略了setter getter相关方法
}

2、定义请求接口
该接口定义了一个函数 getWearther(),该函数会通过HTTP GET(通过@GET方式注解实现)请求去访问服务器的BASE_URL/{city} 路径并把返回的结果封装为 WeatherinfoResult对象返回。
其中URL路径中的 { city } 的值为 getWearther()函数中的参数 city的取值。

/**
 * 首先定义请求接口,即需要请求的操作
 */
public interface IWeatherService {
    @GET("{city}")
    Call<WeatherinfoResult> getWearther(@Path("city") String city);
}

3、 实现Retrofit调用

private void loadWeather() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.weather.com.cn/data/sk/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IWeatherService weatherService = retrofit.create(IWeatherService.class); 
        Call<WeatherinfoResult> repos = weatherService.getWearther("101010100.html");
        repos.enqueue(new Callback<WeatherinfoResult>() {
            @Override
            public void onResponse(Call<WeatherinfoResult> call, Response<WeatherinfoResult> response) {
                Log.v(TAG, "weatherInfo=" + response.body().getWeatherinfo())
            }

            @Override
            public void onFailure(Call<WeatherinfoResult> call, Throwable t) {
                Log.v(TAG, "error=" + t)
            }
        });
    }
retrofit-spring-boot-starter是一个用于整合RetrofitSpring 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的基本用法。你可以根据自己的需求进行配置使用
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值