Android Retrofit 2.0的基本使用

时间:2020-12-04 16:07:22

原文地址:http://blog.magicer.xyz/2017/01/android-retrofit2-basic/

简介

Retrofitsquare公司全家桶中的一员。在okhttp基础上封装的一个网络请求框架。其他废话就不多说了。有几篇不错的文章,可以看一下。
官方介绍
深入浅出 Retrofit,这么牛逼的框架你们还不来看看?
Retrofit2.0

集成

compile 'com.squareup.retrofit2:retrofit:2.1.0'

使用

我们需要为接口地址定义一个接口,如下。当接口为:http://192.168.0.78:8080/login时,我们可以把接口定义为这样。

public interface LoginApi {
@FormUrlEncoded
@POST("/login")
Call<ResponseBody> login(@Field("username")String username, @Field("password")String password);
}

在我们想要做网络请求的时候,这样写:

        Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.78:8080")
.build();
LoginApi login = retrofit.create(LoginApi.class);
retrofit2.Call<ResponseBody> data = login.login(username, password);
data.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(retrofit2.Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
}
else {
}

}
@Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
Log.i(TAG, "retrofit onFailure: " + t.getLocalizedMessage());
}
});

很明显。@POST表明该请求是POST请求。@Field是提交的表单数据。

各注解含义

注解都是在定义接口的时候使用的。做网络请求的代码都是一样的。

@GET

用来表明请求方式为GET请求。

@Path

可以使用在POSTGET请求。
例如:

public interface AnswerApi {
@GET("/word/answer/{barrier}/{stage}/{userId}")
Call<ResponseBody> answer(@Path("barrier")int barrier,
@Path("stage")int stage,
@Path("userId")String userId);
}

@PathMap

Query

可以使用在POSTGET请求。用来配置接口中的参数(?之后的)。

public interface QuestionsApi {
@GET("/word/questions")
Call<ResponseBody> getQuections(@Query("wordIds") String wordIds, @Query("stage")int stage);
}

@QueryMap

some

看下这个就基本上没问题了。

//http://m2.qiushibaike.com/article/list/text?page=1
//基本使用
@GET("/article/list/text?page=1")
retrofit2.Call<ResponseBody> getData();

//动态替换参数,返回解析后的数据
@GET("/article/list/text?")
Call<Bean> getGsonData(@Query("page") int page);

//
@GET("/article/list/text?")
Call<Bean> getNetData(@QueryMap Map<String,String > map);

@GET("/article/list/{type}?/")
Call<Bean> getDataWithPath(@Path("type") String type,@Query("page") int page);

@FormUrlEncoded //POST请求必须添加
@POST("/login?")
Call<ResponseBody> postData(@Field("username") String username,@Field("pwd") String passwrod);

@FormUrlEncoded
@POST("/login?")
Call<ResponseBody> postMapData(@FieldMap Map<String,String> map);

@Body的使用

如下所示,retrofit会把Bean转成json数据进行请求。默认使用的是Gson
可以参考这里 链接

 @POST("/word/records")
Call<WordBrowseRecord> postWordRecords(@Body Bean bean);

ps:Gson怎么控制Date型数据的转换格式呢?看下面代码你就明白了

        Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.HOST)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

自定义Client

在一些情况下我们需要自定义clien,来设置一些请求的参数。那么怎么设置呢? 直接上代码。

        Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("Accept", "*/*")
.addHeader("Cookie", "JSESSIONID")
.build();
return chain.proceed(request);
}
};
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();

//之后在使用的时候
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.HOST)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();