溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android網(wǎng)絡請求框架Retrofit詳解

發(fā)布時間:2020-09-11 20:11:20 來源:腳本之家 閱讀:104 作者:xing-java 欄目:移動開發(fā)

介紹:

Retrofit 是Square公司開發(fā)的一款針對Android網(wǎng)絡請求的框架,Retrofit2底層基于OkHttp實現(xiàn)的,OkHttp現(xiàn)在已經(jīng)得到Google官方認可,大量的app都采用OkHttp做網(wǎng)絡請求。本文使用Retrofit2.0.0版本進行實例演示。

使用Retrofit可以進行GET,POST,PUT,DELETE等請求方式。

同步請求:需要在子線程中完成,會阻塞主線程。

Response response = call.execute().body();

異步請求:請求結果在主線程中回調,可以在onResponse()回調方法進行更新UI。

call.enqueue(Callback callback)

使用步驟:

(1) 創(chuàng)建工程,添加jar:

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0' //這兩個jar版本要一致,否則會有沖突

(2) 創(chuàng)建業(yè)務請求接口,具體代碼如下

/**
 * 創(chuàng)建業(yè)務請求接口
 */

public interface IUserService {
 /**
  * GET請求
  */
 @GET("Servlet/UserServlet")
 Call<User> getUser(@Query("email") String email);

 /**
  * POST請求
  */
 @FormUrlEncoded
 @POST("UserServlet")
 Call<User> postUser(@Field("name") String name, @Field("email") String email);
}


解釋說明:

@GET注解表示GET請求,@Query表示請求參數(shù),將會以key=value(@Query注解參數(shù)名稱為key,調用傳進來的值為value)的方式拼接在url后面.

@POST注解表示POST請求,@FormUrlEncoded將會自動將請求參數(shù)的類型設置為application/x-www-form-urlencoded,@FormUrlEncoded注解不能用于Get請求。@Field注解將每一個請求參數(shù)都存放至請求體中,還可以添加encoded參數(shù),該參數(shù)為boolean型,具體的用法為:
@Field(value = "password", encoded = true) String pwd
encoded參數(shù)為true的話,key-value-pair將會被編碼,即將中文和特殊字符進行編碼轉換.

(3)創(chuàng)建Retrofit對象

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Constant.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
IUserService iUserService = retrofit.create(IUserService.class);


解釋說明:

baseUrl()方法制定網(wǎng)絡請求的固定絕對地址,一般包括請求協(xié)議(如Http)、域名或IP地址、端口號。
創(chuàng)建Retrofit實例時,若沒有配置addConverterFactory(GsonConverterFactory.create())將會回調出JSON字符串,配置了將會回調實體對象。

支持的JSON解析庫:

Gson: compile ‘com.squareup.retrofit2:converter-gson:2.0.1'
Jackson: compile ‘com.squareup.retrofit2:converter-jackson:2.0.1'
Moshi: compile ‘com.squareup.retrofit2:converter-moshi:2.0.1'
Protobuf: compile ‘com.squareup.retrofit2:converter-protobuf:2.0.1'
Wire: compile ‘com.squareup.retrofit2:converter-wire:2.0.1'
Simple XML: compile ‘com.squareup.retrofit2:converter-simplexml:2.0.1'
Scalars (primitives, boxed, and String): compile ‘com.squareup.retrofit2:converter-scalars:2.0.1'

(4) 調用請求方法,并得到Call實例

Call<ResponseBody> call = iUserService.getUser(xing-java@foxmail.com);

(5) 使用Call實例完成同步或異步請求

/**
  * 發(fā)送GET請求
  */
 private void getRequest() {
  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Constant.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  IUserService iUserService = retrofit.create(IUserService.class);
  Call<User> call = iUserService.getUser("xing-java@foxmail.com");
  call.enqueue(new Callback<User>() {
   @Override
   public void onResponse(Call<User> call, Response<User> response) {

    Log.i("MainActivity", "response = " + response);
    User user = response.body();
    resTxtView.setText(user.toString());
   }

   @Override
   public void onFailure(Call<User> call, Throwable t) {

   }
  });
 }


請求方式:

(1)GET 請求:

GET 請求返回 JSON 字符串:

Android網(wǎng)絡請求框架Retrofit詳解

GET 請求返回實體對象:

Android網(wǎng)絡請求框架Retrofit詳解

(2) POST發(fā)送表單:

 /**
  * 發(fā)送POST請求
  */
 private void postRequest() {
  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Constant.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  IUserService iUserService = retrofit.create(IUserService.class);
  Call<User> call = iUserService.postUser("star.tao", "xing-java@foxmail.com");
  call.enqueue(new Callback<User>() {
   @Override
   public void onResponse(Call<User> call, Response<User> response) {
   }

   @Override
   public void onFailure(Call<User> call, Throwable throwable) {

   }
  });


服務端接收到的結果:

Android網(wǎng)絡請求框架Retrofit詳解

(3)文件上傳:

private void uploadFile() {
  Retrofit retrofit = new Retrofit.Builder()
    .addConverterFactory(GsonConverterFactory.create())
    .baseUrl(Constant.BASE_URL)
    .build();
  IUserService iUserService = retrofit.create(IUserService.class);
  File file = new File("/sdcard/s.png");
  RequestBody fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
  MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("upload_file", file.getName(), fileRequestBody);
  String desc = "this is file description";
  RequestBody descRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), desc);
  Call<ResponseBody> call = iUserService.uploadFile(descRequestBody, multipartBody);
  call.enqueue(new Callback<ResponseBody>() {
   @Override
   public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
    Log.i("debug", "upload success");
   }

   @Override
   public void onFailure(Call<ResponseBody> call, Throwable t) {

   }
  });

 }


Android網(wǎng)絡請求框架Retrofit詳解

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI