Retrofit简单使用

最近写了一个天气的Demo,调用开源Weather API:
https://api.openweathermap.org/

在网络请求部分使用了Retrofit,这里学习了解一哈,并做个记录。

一、Retrofit2.0介绍:

GitHub地址

原理的话如图:


Retorfit其实就是一个注解型的网络接口封装,实际调用还是通过OkHttp来实现,只是对他的一层封装。

然后它有很多注解类型:GET、POST、PATH等,我这里只是调用了GET,然后参数通过Query来进行处理。

二、Retorfit具体使用:

1.权限添加:

<uses-permission android:name="android.permission.INTERNET"/>

2.gradle依赖:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

3.创建回调的数据解析类:

public class WeatherModel implements IWeatherModel {

    private IWeatherPresenter mIWeatherPresenter;
    private RetrofitInterface mRetrofitInterface;

    public WeatherModel(IWeatherPresenter IWeatherPresenter) {
        mIWeatherPresenter = IWeatherPresenter;
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constants.BASE_URL)
                .build();
        mRetrofitInterface = retrofit.create(RetrofitInterface.class);
    }

    @Override
    public void getCurrentWeather(final String city) {
        Call<WeatherCurrent> current = mRetrofitInterface.getWeatherCurrent(city, "metric",
                Constants.API_KEY, "zh_cn");
        current.enqueue(new Callback<WeatherCurrent>() {
            @Override
            public void onResponse(Call<WeatherCurrent> call, Response<WeatherCurrent> response) {
                if (response.isSuccessful()) {
                    mIWeatherPresenter.onCurrentWeather(response.body());
                } else {
                    mIWeatherPresenter.onCurrentFail(city);
                }
            }

            @Override
            public void onFailure(Call<WeatherCurrent> call, Throwable t) {
                mIWeatherPresenter.onCurrentFail(t.getMessage());
            }
        });
    }

    @Override
    public void getForecastWeather(final String city) {
        Call<WeatherForecast> forecast = mRetrofitInterface.getWeatherForecast(city, "metric", 20,
                Constants.API_KEY);

        forecast.enqueue(new Callback<WeatherForecast>() {
            @Override
            public void onResponse(Call<WeatherForecast> call, Response<WeatherForecast> response) {
                if (response.isSuccessful()) {
                    mIWeatherPresenter.onForecastWeather(response.body());
                } else {
                    mIWeatherPresenter.onForecastFail(city);
                }
            }

            @Override
            public void onFailure(Call<WeatherForecast> call, Throwable t) {
                mIWeatherPresenter.onForecastFail(t.getMessage());
            }
        });
    }
}

4.创建网络请求的接口:

public interface RetrofitInterface {

    @GET("weather")
    Call<WeatherCurrent> getWeatherCurrent(@Query("q") String cityName,
                                           @Query("units") String units,
                                           @Query("APPID") String ApiId,
                                           @Query("lang") String lang);

    @GET("forecast")
    Call<WeatherForecast> getWeatherForecast(@Query("q") String cityName,
                                             @Query("units") String units,
                                             @Query("cnt") int count,
                                             @Query("APPID") String ApiId);

}

5.定义的接口:

public interface IWeatherModel {

    void getCurrentWeather(String city);

    void getForecastWeather(String city);

}
6.常用的参数类:
public class Constants {

    public static final String API_KEY = "343cb181f9cfa66aa05e5caab8c30cfa";
    public static final String BASE_URL = "https://api.openweathermap.org/data/2.5/";
    public static final String ICON_URL = "http://openweathermap.org/img/w/";

    String key1 = "7e5dcacfa46a733e084fd65210c78e96";
    String key2 = "343cb181f9cfa66aa05e5caab8c30cfa";
    private static final boolean DEBUG = true;
    public static void debug(String str){
        if (DEBUG)
            Log.d("fengjw", str);
    }

}
如此便完成了最简单的Retorfit使用。
完整的项目地址

参考文档:

https://blog.csdn.net/carson_ho/article/details/73732076

https://github.com/square/retrofit

https://openweathermap.org/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Retrofit 是一个开源的 Android 网络请求库,它简化了与 RESTful API 进行交互的过程。你可以使用 Retrofit 来发送网络请求并处理服务器返回的数据。 下面是使用 Retrofit 的一般步骤: 1. 添加 Retrofit 依赖:在你的项目中的 build.gradle 文件中添加以下依赖: ```groovy implementation 'com.squareup.retrofit2:retrofit:2.x.x' ``` 2. 创建 API 接口:定义一个接口来描述你要访问的 API 端点和请求方法。例如: ```java public interface ApiService { @GET("users/{username}") Call<User> getUser(@Path("username") String username); } ``` 3. 创建 Retrofit 实例:使用 Retrofit.Builder 类构建一个 Retrofit 实例,配置基本的 URL 和转换器等。 ```java Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); ``` 4. 创建 API 服务:使用 Retrofit 实例创建一个实现了你的 API 接口的服务。 ```java ApiService apiService = retrofit.create(ApiService.class); ``` 5. 发送网络请求:通过调用 API 服务的方法发送网络请求,并处理返回的结果。 ```java Call<User> call = apiService.getUser("CSDN"); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { User user = response.body(); // 处理返回的用户数据 } else { // 处理请求失败情况 } } @Override public void onFailure(Call<User> call, Throwable t) { // 处理请求失败情况 } }); ``` 这只是一个简单的示例,你可以根据自己的需求进行更复杂的网络请求和数据处理。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值