Android中retrofit網路請求框架使用
阿新 • • 發佈:2018-11-13
Retrofit 是 Square 公司出品的 HTTP 請求庫, 同時是 Square 是最早開源專案之一, Retrofit 是目前 Android 最流行的 Http Client 庫之一, 目前版本是 Retrofit2.0 Beta4, 越來越多 Android 開發者開始使用這個請求庫了
1、配置環境
在build.gradle檔案中匯入依賴包,一個為retrofit包,還有一個為Json轉換包
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
在Android Studio中加入Retrofit包後,系統會自動加入OkHttp包進入專案,Retrofit推出的2.0版本之後,直接強制使用者使用OkHttp做網路請求,所以可以說Retorfit和OkHttp已經是一對兄弟關係。
在AndroidManifest.xml檔案中加入網路請求許可權
2、定義網路請求介面<uses-permission android:name="android.permission.INTERNET" />
例子詳細地址:
http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.4.255.255
public interface ApiService { //獲取詳情資料 @GET("iplookup/iplookup.php?") Call<LocationBean> getLocationData(@Query("format") String format, @Query("ip") String ip); @POST("iplookup/iplookup.php?") Call<LocationBean> postLocationData(@Query("format") String format, @Query("ip") String ip); }
@GET為Http中的get請求,後面請求的引數表示請求的路徑但是不包含域名。
@Post為Http中的post請求,引數與get請求相同,在Post請求上新增@FormUrlEncoded註解,表示以表單的方式來提交引數。
@Query後面表示引數,前面是鍵後面引數為值。
3、定義實體類public class LocationBean {
/**
* ret : 1
* start : -1
* end : -1
* country : 中國
* province : 江蘇
* city : 蘇州
* district :
* isp :
* type :
* desc :
*/
private int ret;
private int start;
private int end;
private String country;
private String province;
private String city;
private String district;
private String isp;
private String type;
private String desc;
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
......
}
可以通過
GsonFormat
轉換器將json資料生成實體類,
GsonFormat
是Android Studio中的外掛,效果如下:
配置方法:
Android studio File->Settings..->Plugins–>Browse repositores..搜尋GsonFormat
安裝外掛,重啟android studio
Retrofit retrofit = new Retrofit.Builder()
//域名
.baseUrl("http://int.dpool.sina.com.cn/")
//增加返回值為Gson的支援(以實體類返回)
.addConverterFactory(GsonConverterFactory.create())
.build();
baseUrl()後面的引數為請求域名,建議寫一個全域性變數,方便後期更改
addConverterFactory(GsonConverterFactory.create())的意思是構建一個返回值支援,後面可通過Call接收到實體類返回值。
4、網路請求
ApiService apiService = retrofit.create(ApiService.class);//這裡採用的是Java的動態代理模式
Call<LocationBean> call = apiService.postLocationData("json", "218.4.255.255");//傳入我們請求的鍵值對的值
call.enqueue(new Callback<LocationBean>() {
@Override
public void onResponse(Call<LocationBean> call, Response<LocationBean> response) {
//伺服器響應
LocationBean bean = response.body();
Log.e("TAG", "body.getMessage()===" + bean.getCity());
content.setText(bean.getCity());
}
@Override
public void onFailure(Call<LocationBean> call, Throwable t) {
//請求失敗
}
});
使用retrofit
方法請求網路,並得到返回值的實體類,
json
解析過程也幫我們完成了
,並且
onResponse和onFailure方法是在
UI執行緒,可以通過回撥直接更新UI介面。
5、示例
public class MainActivity extends Activity {
private Button btn;
private TextView content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
content = (TextView) findViewById(R.id.content);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RetrofitTest();
}
});
}
private void RetrofitTest() {
Retrofit retrofit = new Retrofit.Builder()
//域名
.baseUrl("http://int.dpool.sina.com.cn/")
//增加返回值為Gson的支援(以實體類返回)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);//這裡採用的是Java的動態代理模式
Call<LocationBean> call = apiService.postLocationData("json", "218.4.255.255");//傳入我們請求的鍵值對的值
call.enqueue(new Callback<LocationBean>() {
@Override
public void onResponse(Call<LocationBean> call, Response<LocationBean> response) {
//伺服器響應
LocationBean bean = response.body();
Log.e("TAG", "body.getMessage()===" + bean.getCity());
content.setText(bean.getCity());
}
@Override
public void onFailure(Call<LocationBean> call, Throwable t) {
//請求失敗
}
});
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按鈕" />
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>