1、什麼是Retrofit框架?
它是Square公司開發的現在非常流行的網絡框架,所以我們在導入它的包的時候都可以看到這個公司的名字,目前的版本是2。
特點:
性能好,處理快,使用簡單,Retrofit 是安卓上最流行的HTTP Client庫之一
使用REST API設計風格
支持 NIO(new i/o)
默認使用OKHttp處理網絡請求,我覺得可以看成是OKHttp的增強。
默認使用Gson解析
進入正題。
===================================
2、如何使用?
步驟:
1、導包
compile ‘com.squareup.retrofit2:retrofit:2.0.0-beta4’
同步以後,在External Libraries中會增加:
retrofit-2.0.0-beta4
okhttp-3.0.1
okio-1.6.0
compile ‘com.squareup.retrofit2:converter-gson:2.0.0-beta4’
同步以後,在External Libraries中會增加:
retrofit-2.0.0-beta4
okhttp-3.0.1
okio-1.6.0
gson-2.4
converter-gson-2.0.0-beta4
這些包都是Squareup公司開發的。
所以我們只用compile ‘com.squareup.retrofit2:converter-gson:2.0.0-beta4’也是可以的。
2、瞭解Retrofit2中的網絡訪問常用註解接口,其實這些接口都是在retrofit2.http這個包下面的
1、@GET GET網絡請求方式
2、@POST POST網絡請求方式
3、@Headers() 頭信息參數
4、@Path() 路徑參數,替換url地址中 { } 所括的部分
5、@Query() 查詢參數,將在url地址中追加類似“page=1”的字符串,形成提交給服務端的請求參數
6、@QueryMap 查詢參數集合,將在url地址中追加類似
“type=text&username=abc&password=123”的字符串
7、@FormUrlEncoded 對錶單域中填寫的內容進行編碼處理,避免亂碼
8、@Field() 指定form表單域中每個空間的額name以及相應的數值
9、@FieldMap 表單域集合
10、@Multipart Post提交分塊請求,如果上傳文件,必須指定Multipart
11、@Body Post提交分塊請求
3、代碼步驟:
1、定義一個接口(封裝URL地址和數據請求)
2、實例化Retrofit
3、通過Retrofit實例創建接口服務對象
4、接口服務對象調用接口中方法,獲得Call對象
5、Call對象執行請求(異步、同步請求)
測試Url:
https://api.github.com/users/basil2style
其中https://api.github.com/users/是BASE_URL,也就是基礎地址,basil2style是GET的參數,如果訪問成功會返回給我們一個json字符串:
{
"login": "basil2style",
"id": 1285344,
"avatar_url": "https://avatars.githubusercontent.com/u/1285344?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/basil2style",
"html_url": "https://github.com/basil2style",
"followers_url": "https://api.github.com/users/basil2style/followers",
"following_url": "https://api.github.com/users/basil2style/following{/other_user}",
"gists_url": "https://api.github.com/users/basil2style/gists{/gist_id}",
"starred_url": "https://api.github.com/users/basil2style/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/basil2style/subscriptions",
"organizations_url": "https://api.github.com/users/basil2style/orgs",
"repos_url": "https://api.github.com/users/basil2style/repos",
"events_url": "https://api.github.com/users/basil2style/events{/privacy}",
"received_events_url": "https://api.github.com/users/basil2style/received_events",
"type": "User",
"site_admin": false,
"name": "Basil",
"company": "MakeInfo",
"blog": "http://www.themakeinfo.com",
"location": "Peterborough,ON,Canada",
"email": "[email protected]",
"hireable": true,
"bio": null,
"public_repos": 45,
"public_gists": 4,
"followers": 52,
"following": 145,
"created_at": "2011-12-26T00:17:22Z",
"updated_at": "2016-06-23T20:22:05Z"
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
好,按步驟開始寫代碼
1、定義一個接口(封裝URL地址和數據請求)
RequestServices.java
package com.example.eventbus.retrofittest;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by LHD on 2016/6/25.
*/
public interface RequestServices {
//請求方式爲GET,參數爲basil2style,因爲沒有變量所以下面getString方法也不需要參數
@GET("basil2style")
//定義返回的方法,返回的響應體使用了ResponseBody
Call<ResponseBody> getString();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
我們通常把基礎地址都放在一個類裏,方便調用
Constant.java
package com.example.eventbus.retrofittest;
/**
* Created by LHD on 2016/6/25.
*/
public class Constant {
//baseurl
public final static String URL_BASE = "https://api.github.com/users/";
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
2、實例化Retrofit
//獲取Retrofit對象,設置地址
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL_BASE)
.build();
- 1
- 2
- 3
- 4
3、通過Retrofit實例創建接口服務對象
RequestServices requestServices = retrofit.create(RequestServices.class);
- 1
4、接口服務對象調用接口中方法,獲得Call對象
Call<ResponseBody> call = requestServices.getString();
- 1
5、Call對象執行請求(異步、同步請求)
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()){
try {
Log.i("LHD",response.body().toString());
//返回的結果保存在response.body()中
String result = response.body().string();
//onResponse方法是運行在主線程也就是UI線程的,所以我們可以在這裏
//直接更新UI
textView.setText(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("LHD","訪問失敗");
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
全部代碼:
MainActivity.java
package com.example.eventbus.retrofittest;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
private Context mContext = this;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initRetrofit();
}
private void initView(){
textView = (TextView) findViewById(R.id.tv_retrofit);
}
private void initRetrofit(){
//獲取Retrofit對象,設置地址
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL_BASE)
.build();
Log.i("LHD","1");
RequestServices requestServices = retrofit.create(RequestServices.class);
Call<ResponseBody> call = requestServices.getString();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()){
try {
Log.i("LHD",response.body().toString());
//返回的結果保存在response.body()中
String result = response.body().string();
//onResponse方法是運行在主線程也就是UI線程的,所以我們可以在這裏
//直接更新UI
textView.setText(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("LHD","訪問失敗");
}
});
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
我們的代碼就是將請求的返回值顯示在一個textview上,最後的效果如圖所示:
Retrofit2中GET請求的寫法
1、GET請求,方法中無參數
@GET(“article/page=1”)//並不是全部的Url地址,這個地址會和BaseUrl一起組成一個新的地址。組合的時候要小心。
Call<ResponseBody> getString(); //這個方法名字是自定義的,因爲基本地址裏沒有變量,所以我們的自定義方法裏也沒有參數,其實這個方法的參數就是要添加到這個地址裏的參數。
//ResponseBody是響應體
- 1
- 2
- 3
2、GET請求,方法中指定@Path參數和@Query參數
@Path用於替換url地址中{和}所括的部分。
@Query將在url地址中追加類似“page=1”的字符串,形成提交給服務端的請求參數
@GET(article/list/{type}?)
Call<QiushiModel>getList(
@Path('type')String type,
@Query('page')int page
);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
3、GET請求,提交表單數據。方法中定義@QueryMap參數。
@QueryMap參數將在url地址中追加類似 “type=text&count=30&page=1”的字符串。
@GET("MyWeb/RegServlet")
Call<ResponseBody>getKey(@QueryMap Map<String,String>map);
- 1
- 2
- 3
4、GET請求,方法中無參數。但在@Url裏定義完整URL路徑,這種情況下BaseUrl會被忽略。
@GET("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2299165671,2554860548&fm=116&gp=0.jpg");
Call<ResponsBody>getData();
- 1
- 2
這就是最簡單的retrofit網絡訪問的過程啦。下一篇會更深入的講解,POST請求,獲取網絡圖片,使用Gson解析返回的json文件等等。
demo下載:retrofit2+rxjava+okhttp使用demo。-CSDN下載
http://download.csdn.net/download/baidu_31093133/9696239
<link rel="stylesheet" href="http://csdnimg.cn/release/phoenix/production/markdown_views-993eb3f29c.css">
</div>