Retrofit2.0 的使用

本文介绍如何在Android应用中使用Retrofit 2.0进行网络请求,包括配置Retrofit实例、创建接口定义请求方法、同步与异步调用方式,以及取消请求等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题外话:

最近发现群里的小伙伴们,对Retrofit的讨论越来越多了起来。然而用惯了Volley的我直接就懵了,fit我知道,前面加个Restro我就表示不认识了。而android 6.0的出现则毫无疑问的捅了volley一刀,volley是基于HttpClient或者HttpUrlConnection的,而android 6.0则把HttpClient给杠了(废弃了HttpClient)。直接给人营造出一种感觉,volley吃枣药丸。坚持不住了,那就换个请求框架吧,网上一查,retrofit似乎是一中很不错的感觉,基于okhttp(仅针对Retrofit 2.0),还适用于越来越流行的RxJava,似乎能战几年的样子。(注:本文基于Android Studio)

设置:

1、权限设置:在AndroidManifest中加入如下获取权限语句(网络权限,原因不解释了,大家都知道的)
<uses-permission android:name="android.permission.INTERNET"/>
2、在build.gradle中添加Retrofit的远程依赖,并同步。(由于Retrofit 2.0不再默认使用Gson,故此引入"converter-gson",对数据做json处理。因为Retrofit 2.0默认okhttp,故此Android Studio会自动添加okhttp和okio的依赖)
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'

使用:

1、创建Retrofit实例
/**
* baseUrl:请求链接(2.0似乎必须以"/"结束了)
* addConverterFactory:添加接收数据处理方式
* GsonConverterFactory.create():表示接收json结果,并将数据处理为DAO
* Square提供多种Converter:
* 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
*/
Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://gc.ditu.aliyun.com/")
                        .addConverter`这里写代码片`Factory(GsonConverterFactory.create())       
                        .build();
2、创建接口:

(1)使用@get向服务器请求数据(注:不再区分同步与异步)
/**
*使用绝对URL:"http://gc.ditu.aliyun.com/geocoding?a=苏州市"
*接口使用:Call<LoginInfo> loginInfo = service.loadInfo();
*/
public interface QuestService{
    @GET("http://gc.ditu.aliyun.com/geocoding?a=苏州市")
    Call<LoginInfo> loadInfo();
}
/**
*使用相对URL:"geocoding?a=苏州市"
*接口使用:Call<LoginInfo> loginInfo = service.loadInfo();
*/
public interface QuestService{
    @GET("geocoding?a=苏州市")
    Call<LoginInfo> loadInfo();
}
/**
*{a}:动态设置相对路径
*@Path("a"):表示用a的值替换{a}
*接口使用:Call<LoginInfo> loginInfo = service.loadInfo("geocoding");
*/
public interface QuestService{
    @GET("{a}?a=苏州市")
    Call<LoginInfo> loadInfo(@Path("a") String a;
}
/**
*@Query("a"):表示带参,参数名为"a",值为 "String a"
*接口使用:Call<LoginInfo> loginInfo = service.loadInfo("苏州市");
*/
public interface QuestService3{
    @GET("geocoding")
    Call<LoginInfo> loadInfo(@Query("a") String a);
}
/**
*@QueryMap Map<String, String>:所带参数为键值对。
*接口使用:
*   HashMap<String, String> map = new HashMap<String, String>();
*   map.put("a", "苏州市");
*   Call<LoginInfo> loginInfo = service.loadInfo(map);
*/
public interface QuestService3{
    @GET("geocoding")
    Call<LoginInfo> loadInfo(@QueryMap Map<String, String> map);
}
(2)、具体使用形式:

同步:
Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://gc.ditu.aliyun.com/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
QuestService service = retrofit.create(QuestService.class);
/**
*final Call<LoginInfo> loginInfo = service.loadInfo();
*根据自己选择的@GET使用方式来确定"接口使用"
*/
final Call<LoginInfo> loginInfo = service.loadInfo();
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
                Response<LoginInfo> info = loginInfo.execute();
                System.out.println(info.body().toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
}).start();
异步:
Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://gc.ditu.aliyun.com/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
QuestService service = retrofit.create(QuestService.class);
final Call<LoginInfo> loginInfo = service.loadInfo();
loginInfo.enqueue(new Callback<LoginInfo>() {
    @Override
    public void onResponse(Call<LoginInfo> call, Response<LoginInfo>   response){
            LoginInfo info = respnse.body();
         }

    @Override
    public void onFailure(Call<LoginInfo> call, Throwable t) {
    }
});
(3)、@POST, @PUT等的使用,由于暂时缺乏验证环境,就不写出来了。

3、取消请求
loginInfo.cancel();

结语

关于Retrofit的使用,本篇只讲述了一些基本的使用方式,后面如果遇到更复杂的,再继续补充吧!

参考

Retrofit 2.0:有史以来最大的改进

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值