Retrofit

認識Retrofit

關於Retrofit

Retrofit是使用Okhttp做網路請求並做介面封裝,特別的是其規範的REST框架讓程式高度解耦,好寫易維護。 另外它跟OkHttp同為Square公司出品,兩者可以完美整合發揮更多功能。

在这里插入图片描述

使用方法

添加依賴

// retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// 如果用到gson解析 需要新增下面的依賴
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
 // retrofit使用Okhttp連線
 compile 'com.squareup.okhttp3:okhttp:3.1.2'

初始化 創建Retrofit實體

public class NetWork {

private static Retrofit retrofit;
public static Retrofit getRetrofit(){

if(retrofit == null){
	Retrofit.Builder builder = new Retrofit.Builder(); //建立Retrfit構建器
	retrofit = builder.baseUrl("http://apis.com.tw/")  //指定網路請求的baseUrl
	.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
	.addConverterFactory(GsonConverterFactory.create()) //返回的資料通過Gson解析
	.build();
}else{
	return retrofit;
	}
}

  • 除了通過Gson解析還可以使用其它的方式解析,需要的依賴也不同,有如下幾種:
    Gson: com.squareup.retrofit:converter-gson
    com.squareup.retrofit:converter-gson Jackson:
    com.squareup.retrofit:converter-jackson Moshi:
    com.squareup.retrofit:converter-moshi Protobuf:
    com.squareup.retrofit:converter-protobuf Wire:
    com.squareup.retrofit:converter-wire Simple XML:
    com.squareup.retrofit:converter-simplexml

Retrofit需要把Http的請求介面封裝到一個介面檔案中。

public interface NetInterface {
// API~獲取使用者資訊
@GET("mobile/get")
Call<Bean> getUserInfo(@Header("token") String token);
}

其中Bean是根據請求的結果建立的物件
方法前新增@GET註解表示當前請求是Get方式請求,連結的地址是baseUrl ”mobile/get”,baseUrl會在初始化Retrofit的時候指定。

請求方式
@POST 表明這是post請求
@PUT 表明這是put請求
@DELETE 表明這是delete請求
@PATCH 表明這是一個patch請求,該請求是對put請求的補充,用於更新區域性資源
@HEAD 表明這是一個head請求
@OPTIONS 表明這是一個option請求
@HTTP 通用註解,可以替換以上所有的註解,其擁有三個屬性:method,path,hasBody

常用註解
如某隻API不吃Base url的時候:
@Url:使用全路徑複寫baseUrl,適用於非統一baseUrl的場景。

@GET Call<ResponseBody> getUser(@Url String url);

@Streaming:用於下載大檔案。

@Streaming @GET Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);
//獲取資料的程式碼
ResponseBody body = response.body();
long fileSize = body.contentLength();
InputStream inputStream = body.byteStream();

@Path:URL佔位符,用於替換和動態更新,相應的引數必須使用相同的字串被@Path進行註釋

//實際請求地址會給句groupId的值發生變化--> http://baseurl/group/groupId/users
@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId);

@QueryMap:查詢引數,和@Query類似,區別就是後面需要Map集合引數。

Call<List<News>> getNews((@QueryMap(encoded=true) Map<String, String> options);

@Body:用於POST請求體,將例項物件根據轉換方式轉換為對應的json字串引數,這個轉化方式是GsonConverterFactory定義的。

@POST("add")
Call<List<User>> addUser(@Body User user);

@Field,@FieldMap:Post方式傳遞簡單的鍵值對,需要新增@FormUrlEncoded表示表單提交

@FormUrlEncoded @POST("user/edit") Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

@Part,@PartMap:用於POST檔案上傳,其中@Part MultipartBody.Part代表檔案,@Part(“key”) RequestBody代表引數,需要新增@Multipart表示支援檔案上傳的表單。

@Multipart
@POST("upload")
Call<ResponseBody> upload(@Part("description") RequestBody description,
@Part MultipartBody.Part file);

基本使用請求範例

// init
NetInterface netInterface = NetWork.getRetrofit().create(NetInterface.class);

// Call Api
netInterface.getAddress(editText.getText().toString(),"app key")
.enqueue(new Callback<Bean>() {
	@Override
	public void onResponse(Call<Bean> call, Response<Bean> response) {
	//請求成功
	Bean bean = response.body();
}
	@Override
	public void onFailure(Call<Bean> call, Throwable t) {
	//請求失敗
}
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值