Retrofit:Android和Java的類型安全的HTTP客戶端。
Introduction:
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
2.Retrofit類去實現GitHubService的接口
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
Call<List<Repo>> repos = service.listRepos("octocat");
1.支持URL參數替換和查詢參數
2.對象轉換爲請求主體(例如,JSON,協議緩衝區)
3.Multipart請求主體和文件上傳
API Declaration:
@GET("users/list")
還可以指定URL的查詢參數,例如:
@GET("users/list?sort=desc")
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
查詢參數也可以被添加,例如:
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
對於複雜的查詢參數組合可以使用map,例如:
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
@POST("users/new")
Call<User> createUser(@Body User user);
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
在Android中,回調函數將在主線程上執行,在JVM虛擬機上,回調函數會發生在同一線程執行HTTP請求。
Retrofit Configuration(配置)
轉換器可以添加到其他類型的支持,以下是6個常用的序列化庫:
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
Retrofit的基本配置項目中的使用
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
一個簡單使用Retrofit中的例子
public interface UserCardnoService {
//基本信息查詢
@GET("/idcard/index")
Call<InforBean> getInfoResult(@Query("key") String key, @Query("cardno") String cardno);
//信息是否泄漏
@GET("/idcard/leak")
Call<LeakBean> getLeakResult(@Query("key") String key, @Query("cardno") String cardno);
//身份證是否掛失
@GET("/idcard/loss")
Call<LossBean> getLossResult(@Query("key") String key, @Query("cardno") String cardno);
}
3.創建實體類,這裏放的實體類是基本信息的查詢:
public class InforBean {
/**
* resultcode : 200
* reason : 成功的返回
* result : {"area":"浙江省溫州市平陽縣","sex":"男","birthday":"1989年03月08日"}
*/
public String resultcode;
public String reason;
public int error_code;
/**
* area : 浙江省溫州市平陽縣
* sex : 男
* birthday : 1989年03月08日
*/
public ResultBean result;
public static class ResultBean {
public String area;
public String sex;
public String birthday;
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
public String getResultcode() {
return resultcode;
}
public void setResultcode(String resultcode) {
this.resultcode = resultcode;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
}
public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = "UserInfoActivity";
private EditText mEtInput;
private Button btnQuery;
private TextView mTvArea;
private TextView mTvSex;
private TextView mTvBirthday;
private LinearLayout llInfo;
private String mCardno;
private Context mContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = UserInfoActivity.this;
setContentView(R.layout.base_layout);
initView();
}
private void initView() {
mEtInput = (EditText) findViewById(R.id.etInput);
btnQuery = (Button) findViewById(R.id.btnQuery);
mTvArea = (TextView) findViewById(R.id.tvArea);
mTvSex = (TextView) findViewById(R.id.tvSex);
mTvBirthday = (TextView) findViewById(R.id.tvBirthday);
llInfo = (LinearLayout) findViewById(R.id.ll_Info);
btnQuery.setOnClickListener(this);
}
@Override
public void onClick(View v) {
mCardno = mEtInput.getText().toString().trim();
if (!mCardno.matches(RegexpUtils.USER_CARD)) {
Toast.makeText(mContext, "輸入有誤,請重新輸入!", Toast.LENGTH_SHORT).show();
} else {
getNetData();
}
}
private void getNetData() {
//構建rtrofit實例
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(GlobalContact.BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
UserCardnoService infoService = retrofit.create(UserCardnoService.class);
Call<InforBean> call = infoService.getInfoResult(GlobalContact.KEY, mCardno);
call.enqueue(new Callback<InforBean>() {
@Override
public void onResponse(Call<InforBean> call, Response<InforBean> response) {
Log.i(TAG, "onResponse: " + response.body().toString());
if (response.isSuccessful()) {
llInfo.setVisibility(View.VISIBLE);
//對數據進行賦值
mTvArea.setText(response.body().result.area);
mTvSex.setText(response.body().result.sex);
mTvBirthday.setText(response.body().result.birthday);
} else {
llInfo.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call<InforBean> call, Throwable t) {
Log.i(TAG, "onFailure: " + t.toString());
}
});
}
}